From 755b5082c72a09863a1dc159177a8d7af980cf55 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Mon, 18 Jun 2012 22:38:34 +0530 Subject: [PATCH 01/52] Possible fix for the 'moveFiles' function only moving one file over before getting stuck. Changes shutil.move(src,dest) to use a filename for the dest instead of the parent directory --- headphones/postprocessor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/headphones/postprocessor.py b/headphones/postprocessor.py index 5a494cf1..571f4ea7 100644 --- a/headphones/postprocessor.py +++ b/headphones/postprocessor.py @@ -404,7 +404,7 @@ def moveFiles(albumpath, release, tracks): logger.warn('Error renaming %s: %s' % (files, e)) break try: - shutil.move(os.path.join(r, files), destination_path) + shutil.move(os.path.join(r, files), os.path.join(destination_path, files)) except shutil.Error, e: logger.warn('Error moving file %s: %s' % (files, e)) From a3f6d90f74c65f4061fc76c41f1218fc8b24be11 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 19 Jun 2012 12:46:44 +0530 Subject: [PATCH 02/52] CoSome general cleanup. Converted all tabs to spaces for consistency, removed templates.py as it was no longer being used --- headphones/__init__.py | 74 +-- headphones/albumart.py | 12 +- headphones/api.py | 568 ++++++++-------- headphones/db.py | 126 ++-- headphones/helpers.py | 214 +++--- headphones/importer.py | 684 ++++++++++---------- headphones/lastfm.py | 326 +++++----- headphones/librarysync.py | 374 +++++------ headphones/logger.py | 112 ++-- headphones/lyrics.py | 92 +-- headphones/mb.py | 6 +- headphones/music_encoder.py | 238 +++---- headphones/notifiers.py | 202 +++--- headphones/postprocessor.py | 1218 +++++++++++++++++------------------ headphones/sab.py | 2 +- headphones/searcher.py | 505 ++++++++------- headphones/templates.py | 440 ------------- headphones/updater.py | 20 +- headphones/versioncheck.py | 390 +++++------ headphones/webserve.py | 1090 +++++++++++++++---------------- headphones/webstart.py | 68 +- 21 files changed, 3160 insertions(+), 3601 deletions(-) delete mode 100644 headphones/templates.py diff --git a/headphones/__init__.py b/headphones/__init__.py index 606f14f8..793b92c0 100644 --- a/headphones/__init__.py +++ b/headphones/__init__.py @@ -325,7 +325,7 @@ def initialize(): INTERFACE = check_setting_str(CFG, 'General', 'interface', 'default') FOLDER_PERMISSIONS = check_setting_str(CFG, 'General', 'folder_permissions', '0755') - + ENCODERFOLDER = check_setting_str(CFG, 'General', 'encoderfolder', '') ENCODER = check_setting_str(CFG, 'General', 'encoder', 'ffmpeg') BITRATE = check_setting_int(CFG, 'General', 'bitrate', 192) @@ -363,7 +363,7 @@ def initialize(): # update folder formats in the config & bump up config version if CONFIG_VERSION == '0': from headphones.helpers import replace_all - file_values = { 'tracknumber': 'Track', 'title': 'Title','artist' : 'Artist', 'album' : 'Album', 'year' : 'Year' } + file_values = { 'tracknumber': 'Track', 'title': 'Title','artist' : 'Artist', 'album' : 'Album', 'year' : 'Year' } folder_values = { 'artist' : 'Artist', 'album':'Album', 'year' : 'Year', 'releasetype' : 'Type', 'first' : 'First', 'lowerfirst' : 'first' } FILE_FORMAT = replace_all(FILE_FORMAT, file_values) FOLDER_FORMAT = replace_all(FOLDER_FORMAT, folder_values) @@ -372,34 +372,34 @@ def initialize(): if CONFIG_VERSION == '1': - from headphones.helpers import replace_all + from headphones.helpers import replace_all - file_values = { 'Track': '$Track', - 'Title': '$Title', - 'Artist': '$Artist', - 'Album': '$Album', - 'Year': '$Year', - 'track': '$track', - 'title': '$title', - 'artist': '$artist', - 'album': '$album', - 'year': '$year' - } - folder_values = { 'Artist': '$Artist', - 'Album': '$Album', - 'Year': '$Year', - 'Type': '$Type', - 'First': '$First', - 'artist': '$artist', - 'album': '$album', - 'year': '$year', - 'type': '$type', - 'first': '$first' - } - FILE_FORMAT = replace_all(FILE_FORMAT, file_values) - FOLDER_FORMAT = replace_all(FOLDER_FORMAT, folder_values) - - CONFIG_VERSION = '2' + file_values = { 'Track': '$Track', + 'Title': '$Title', + 'Artist': '$Artist', + 'Album': '$Album', + 'Year': '$Year', + 'track': '$track', + 'title': '$title', + 'artist': '$artist', + 'album': '$album', + 'year': '$year' + } + folder_values = { 'Artist': '$Artist', + 'Album': '$Album', + 'Year': '$Year', + 'Type': '$Type', + 'First': '$First', + 'artist': '$artist', + 'album': '$album', + 'year': '$year', + 'type': '$type', + 'first': '$first' + } + FILE_FORMAT = replace_all(FILE_FORMAT, file_values) + FOLDER_FORMAT = replace_all(FOLDER_FORMAT, folder_values) + + CONFIG_VERSION = '2' if not LOG_DIR: LOG_DIR = os.path.join(DATA_DIR, 'logs') @@ -435,12 +435,12 @@ def initialize(): # Check for new versions if CHECK_GITHUB_ON_STARTUP: - try: - LATEST_VERSION = versioncheck.checkGithub() - except: - LATEST_VERSION = CURRENT_VERSION + try: + LATEST_VERSION = versioncheck.checkGithub() + except: + LATEST_VERSION = CURRENT_VERSION else: - LATEST_VERSION = CURRENT_VERSION + LATEST_VERSION = CURRENT_VERSION __INITIALIZED__ = True return True @@ -766,9 +766,9 @@ def shutdown(restart=False, update=False): config_write() if not restart and not update: - logger.info('Headphones is shutting down...') + logger.info('Headphones is shutting down...') if update: - logger.info('Headphones is updating...') + logger.info('Headphones is updating...') try: versioncheck.update() except Exception, e: @@ -779,7 +779,7 @@ def shutdown(restart=False, update=False): os.remove(PIDFILE) if restart: - logger.info('Headphones is restarting...') + logger.info('Headphones is restarting...') popen_list = [sys.executable, FULL_PATH] popen_list += ARGS if '--nolaunch' not in popen_list: diff --git a/headphones/albumart.py b/headphones/albumart.py index ace34556..08773870 100644 --- a/headphones/albumart.py +++ b/headphones/albumart.py @@ -2,9 +2,9 @@ from headphones import db def getAlbumArt(albumid): - myDB = db.DBConnection() - asin = myDB.action('SELECT AlbumASIN from albums WHERE AlbumID=?', [albumid]).fetchone()[0] - - url = 'http://ec1.images-amazon.com/images/P/%s.01.LZZZZZZZ.jpg' % asin - - return url \ No newline at end of file + myDB = db.DBConnection() + asin = myDB.action('SELECT AlbumASIN from albums WHERE AlbumID=?', [albumid]).fetchone()[0] + + url = 'http://ec1.images-amazon.com/images/P/%s.01.LZZZZZZZ.jpg' % asin + + return url diff --git a/headphones/api.py b/headphones/api.py index c6f132ed..852249c9 100644 --- a/headphones/api.py +++ b/headphones/api.py @@ -7,295 +7,295 @@ from xml.dom.minidom import Document import copy cmd_list = [ 'getIndex', 'getArtist', 'getAlbum', 'getUpcoming', 'getWanted', 'getSimilar', 'getHistory', 'getLogs', - 'findArtist', 'findAlbum', 'addArtist', 'delArtist', 'pauseArtist', 'resumeArtist', 'refreshArtist', - 'queueAlbum', 'unqueueAlbum', 'forceSearch', 'forceProcess', 'getVersion', 'checkGithub', - 'shutdown', 'restart', 'update', ] + 'findArtist', 'findAlbum', 'addArtist', 'delArtist', 'pauseArtist', 'resumeArtist', 'refreshArtist', + 'queueAlbum', 'unqueueAlbum', 'forceSearch', 'forceProcess', 'getVersion', 'checkGithub', + 'shutdown', 'restart', 'update', ] class Api(object): - def __init__(self): - - self.apikey = None - self.cmd = None - self.id = None - - self.kwargs = None + def __init__(self): + + self.apikey = None + self.cmd = None + self.id = None + + self.kwargs = None - self.data = None + self.data = None - self.callback = None + self.callback = None - - def checkParams(self,*args,**kwargs): - - if not headphones.API_ENABLED: - self.data = 'API not enabled' - return - if not headphones.API_KEY: - self.data = 'API key not generated' - return - if len(headphones.API_KEY) != 32: - self.data = 'API key not generated correctly' - return - - if 'apikey' not in kwargs: - self.data = 'Missing api key' - return - - if kwargs['apikey'] != headphones.API_KEY: - self.data = 'Incorrect API key' - return - else: - self.apikey = kwargs.pop('apikey') - - if 'cmd' not in kwargs: - self.data = 'Missing parameter: cmd' - return - - if kwargs['cmd'] not in cmd_list: - self.data = 'Unknown command: %s' % kwargs['cmd'] - return - else: - self.cmd = kwargs.pop('cmd') - - self.kwargs = kwargs - self.data = 'OK' + + def checkParams(self,*args,**kwargs): + + if not headphones.API_ENABLED: + self.data = 'API not enabled' + return + if not headphones.API_KEY: + self.data = 'API key not generated' + return + if len(headphones.API_KEY) != 32: + self.data = 'API key not generated correctly' + return + + if 'apikey' not in kwargs: + self.data = 'Missing api key' + return + + if kwargs['apikey'] != headphones.API_KEY: + self.data = 'Incorrect API key' + return + else: + self.apikey = kwargs.pop('apikey') + + if 'cmd' not in kwargs: + self.data = 'Missing parameter: cmd' + return + + if kwargs['cmd'] not in cmd_list: + self.data = 'Unknown command: %s' % kwargs['cmd'] + return + else: + self.cmd = kwargs.pop('cmd') + + self.kwargs = kwargs + self.data = 'OK' - def fetchData(self): - - if self.data == 'OK': - logger.info('Recieved API command: ' + self.cmd) - methodToCall = getattr(self, "_" + self.cmd) - result = methodToCall(**self.kwargs) - if 'callback' not in self.kwargs: - if type(self.data) == type(''): - return self.data - else: - return simplejson.dumps(self.data) - else: - self.callback = self.kwargs['callback'] - self.data = simplejson.dumps(self.data) - self.data = self.callback + '(' + self.data + ');' - return self.data - else: - return self.data - - def _dic_from_query(self,query): - - myDB = db.DBConnection() - rows = myDB.select(query) - - rows_as_dic = [] - - for row in rows: - row_as_dic = dict(zip(row.keys(), row)) - rows_as_dic.append(row_as_dic) - - return rows_as_dic - - def _getIndex(self, **kwargs): - - self.data = self._dic_from_query('SELECT * from artists order by ArtistSortName COLLATE NOCASE') - return - - def _getArtist(self, **kwargs): - - if 'id' not in kwargs: - self.data = 'Missing parameter: id' - return - else: - self.id = kwargs['id'] - - artist = self._dic_from_query('SELECT * from artists WHERE ArtistID="' + self.id + '"') - albums = self._dic_from_query('SELECT * from albums WHERE ArtistID="' + self.id + '" order by ReleaseDate DESC') - - self.data = { 'artist': artist, 'albums': albums } - return - - def _getAlbum(self, **kwargs): - - if 'id' not in kwargs: - self.data = 'Missing parameter: id' - return - else: - self.id = kwargs['id'] - - album = self._dic_from_query('SELECT * from albums WHERE AlbumID="' + self.id + '"') - tracks = self._dic_from_query('SELECT * from tracks WHERE AlbumID="' + self.id + '"') - description = self._dic_from_query('SELECT * from descriptions WHERE ReleaseGroupID="' + self.id + '"') - - self.data = { 'album' : album, 'tracks' : tracks, 'description' : description } - return - - def _getHistory(self, **kwargs): - self.data = self._dic_from_query('SELECT * from snatched order by DateAdded DESC') - return - - def _getUpcoming(self, **kwargs): - self.data = self._dic_from_query("SELECT * from albums WHERE ReleaseDate > date('now') order by ReleaseDate DESC") - return - - def _getWanted(self, **kwargs): - self.data = self._dic_from_query("SELECT * from albums WHERE Status='Wanted'") - return - - def _getSimilar(self, **kwargs): - self.data = self._dic_from_query('SELECT * from lastfmcloud') - return - - def _getLogs(self, **kwargs): - pass - - def _findArtist(self, **kwargs): - if 'name' not in kwargs: - self.data = 'Missing parameter: name' - return - if 'limit' in kwargs: - limit = kwargs['limit'] - else: - limit=50 - - self.data = mb.findArtist(kwargs['name'], limit) + def fetchData(self): + + if self.data == 'OK': + logger.info('Recieved API command: ' + self.cmd) + methodToCall = getattr(self, "_" + self.cmd) + result = methodToCall(**self.kwargs) + if 'callback' not in self.kwargs: + if type(self.data) == type(''): + return self.data + else: + return simplejson.dumps(self.data) + else: + self.callback = self.kwargs['callback'] + self.data = simplejson.dumps(self.data) + self.data = self.callback + '(' + self.data + ');' + return self.data + else: + return self.data + + def _dic_from_query(self,query): + + myDB = db.DBConnection() + rows = myDB.select(query) + + rows_as_dic = [] + + for row in rows: + row_as_dic = dict(zip(row.keys(), row)) + rows_as_dic.append(row_as_dic) + + return rows_as_dic + + def _getIndex(self, **kwargs): + + self.data = self._dic_from_query('SELECT * from artists order by ArtistSortName COLLATE NOCASE') + return + + def _getArtist(self, **kwargs): + + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + artist = self._dic_from_query('SELECT * from artists WHERE ArtistID="' + self.id + '"') + albums = self._dic_from_query('SELECT * from albums WHERE ArtistID="' + self.id + '" order by ReleaseDate DESC') + + self.data = { 'artist': artist, 'albums': albums } + return + + def _getAlbum(self, **kwargs): + + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + album = self._dic_from_query('SELECT * from albums WHERE AlbumID="' + self.id + '"') + tracks = self._dic_from_query('SELECT * from tracks WHERE AlbumID="' + self.id + '"') + description = self._dic_from_query('SELECT * from descriptions WHERE ReleaseGroupID="' + self.id + '"') + + self.data = { 'album' : album, 'tracks' : tracks, 'description' : description } + return + + def _getHistory(self, **kwargs): + self.data = self._dic_from_query('SELECT * from snatched order by DateAdded DESC') + return + + def _getUpcoming(self, **kwargs): + self.data = self._dic_from_query("SELECT * from albums WHERE ReleaseDate > date('now') order by ReleaseDate DESC") + return + + def _getWanted(self, **kwargs): + self.data = self._dic_from_query("SELECT * from albums WHERE Status='Wanted'") + return + + def _getSimilar(self, **kwargs): + self.data = self._dic_from_query('SELECT * from lastfmcloud') + return + + def _getLogs(self, **kwargs): + pass + + def _findArtist(self, **kwargs): + if 'name' not in kwargs: + self.data = 'Missing parameter: name' + return + if 'limit' in kwargs: + limit = kwargs['limit'] + else: + limit=50 + + self.data = mb.findArtist(kwargs['name'], limit) - def _findAlbum(self, **kwargs): - if 'name' not in kwargs: - self.data = 'Missing parameter: name' - return - if 'limit' in kwargs: - limit = kwargs['limit'] - else: - limit=50 - - self.data = mb.findRelease(kwargs['name'], limit) - - def _addArtist(self, **kwargs): - if 'id' not in kwargs: - self.data = 'Missing parameter: id' - return - else: - self.id = kwargs['id'] - - try: - importer.addArtisttoDB(self.id) - except Exception, e: - self.data = e - - return - - def _delArtist(self, **kwargs): - if 'id' not in kwargs: - self.data = 'Missing parameter: id' - return - else: - self.id = kwargs['id'] - - myDB = db.DBConnection() - myDB.action('DELETE from artists WHERE ArtistID="' + self.id + '"') - myDB.action('DELETE from albums WHERE ArtistID="' + self.id + '"') - myDB.action('DELETE from tracks WHERE ArtistID="' + self.id + '"') - - def _pauseArtist(self, **kwargs): - if 'id' not in kwargs: - self.data = 'Missing parameter: id' - return - else: - self.id = kwargs['id'] - - myDB = db.DBConnection() - controlValueDict = {'ArtistID': self.id} - newValueDict = {'Status': 'Paused'} - myDB.upsert("artists", newValueDict, controlValueDict) - - def _resumeArtist(self, **kwargs): - if 'id' not in kwargs: - self.data = 'Missing parameter: id' - return - else: - self.id = kwargs['id'] - - myDB = db.DBConnection() - controlValueDict = {'ArtistID': self.id} - newValueDict = {'Status': 'Active'} - myDB.upsert("artists", newValueDict, controlValueDict) - - def _refreshArtist(self, **kwargs): - if 'id' not in kwargs: - self.data = 'Missing parameter: id' - return - else: - self.id = kwargs['id'] - - try: - importer.addArtisttoDB(self.id) - except Exception, e: - self.data = e - - return - - def _queueAlbum(self, **kwargs): - - if 'id' not in kwargs: - self.data = 'Missing parameter: id' - return - else: - self.id = kwargs['id'] - - if 'new' in kwargs: - new = kwargs['new'] - else: - new = False - - if 'lossless' in kwargs: - lossless = kwargs['lossless'] - else: - lossless = False - - myDB = db.DBConnection() - controlValueDict = {'AlbumID': self.id} - if lossless: - newValueDict = {'Status': 'Wanted Lossless'} - else: - newValueDict = {'Status': 'Wanted'} - myDB.upsert("albums", newValueDict, controlValueDict) - searcher.searchforalbum(self.id, new) - - def _unqueueAlbum(self, **kwargs): - - if 'id' not in kwargs: - self.data = 'Missing parameter: id' - return - else: - self.id = kwargs['id'] - - myDB = db.DBConnection() - controlValueDict = {'AlbumID': self.id} - newValueDict = {'Status': 'Skipped'} - myDB.upsert("albums", newValueDict, controlValueDict) - - def _forceSearch(self, **kwargs): - searcher.searchforalbum() - - def _forceProcess(self, **kwargs): - postprocessor.forcePostProcess() - - def _getVersion(self, **kwargs): - self.data = { - 'git_path' : headphones.GIT_PATH, - 'install_type' : headphones.INSTALL_TYPE, - 'current_version' : headphones.CURRENT_VERSION, - 'latest_version' : headphones.LATEST_VERSION, - 'commits_behind' : headphones.COMMITS_BEHIND, - } - - def _checkGithub(self, **kwargs): - versioncheck.checkGithub() - self._getVersion() - - def _shutdown(self, **kwargs): - headphones.SIGNAL = 'shutdown' - - def _restart(self, **kwargs): - headphones.SIGNAL = 'restart' - - def _update(self, **kwargs): - headphones.SIGNAL = 'update' \ No newline at end of file + def _findAlbum(self, **kwargs): + if 'name' not in kwargs: + self.data = 'Missing parameter: name' + return + if 'limit' in kwargs: + limit = kwargs['limit'] + else: + limit=50 + + self.data = mb.findRelease(kwargs['name'], limit) + + def _addArtist(self, **kwargs): + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + try: + importer.addArtisttoDB(self.id) + except Exception, e: + self.data = e + + return + + def _delArtist(self, **kwargs): + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + myDB = db.DBConnection() + myDB.action('DELETE from artists WHERE ArtistID="' + self.id + '"') + myDB.action('DELETE from albums WHERE ArtistID="' + self.id + '"') + myDB.action('DELETE from tracks WHERE ArtistID="' + self.id + '"') + + def _pauseArtist(self, **kwargs): + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + myDB = db.DBConnection() + controlValueDict = {'ArtistID': self.id} + newValueDict = {'Status': 'Paused'} + myDB.upsert("artists", newValueDict, controlValueDict) + + def _resumeArtist(self, **kwargs): + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + myDB = db.DBConnection() + controlValueDict = {'ArtistID': self.id} + newValueDict = {'Status': 'Active'} + myDB.upsert("artists", newValueDict, controlValueDict) + + def _refreshArtist(self, **kwargs): + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + try: + importer.addArtisttoDB(self.id) + except Exception, e: + self.data = e + + return + + def _queueAlbum(self, **kwargs): + + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + if 'new' in kwargs: + new = kwargs['new'] + else: + new = False + + if 'lossless' in kwargs: + lossless = kwargs['lossless'] + else: + lossless = False + + myDB = db.DBConnection() + controlValueDict = {'AlbumID': self.id} + if lossless: + newValueDict = {'Status': 'Wanted Lossless'} + else: + newValueDict = {'Status': 'Wanted'} + myDB.upsert("albums", newValueDict, controlValueDict) + searcher.searchforalbum(self.id, new) + + def _unqueueAlbum(self, **kwargs): + + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + myDB = db.DBConnection() + controlValueDict = {'AlbumID': self.id} + newValueDict = {'Status': 'Skipped'} + myDB.upsert("albums", newValueDict, controlValueDict) + + def _forceSearch(self, **kwargs): + searcher.searchforalbum() + + def _forceProcess(self, **kwargs): + postprocessor.forcePostProcess() + + def _getVersion(self, **kwargs): + self.data = { + 'git_path' : headphones.GIT_PATH, + 'install_type' : headphones.INSTALL_TYPE, + 'current_version' : headphones.CURRENT_VERSION, + 'latest_version' : headphones.LATEST_VERSION, + 'commits_behind' : headphones.COMMITS_BEHIND, + } + + def _checkGithub(self, **kwargs): + versioncheck.checkGithub() + self._getVersion() + + def _shutdown(self, **kwargs): + headphones.SIGNAL = 'shutdown' + + def _restart(self, **kwargs): + headphones.SIGNAL = 'restart' + + def _update(self, **kwargs): + headphones.SIGNAL = 'update' diff --git a/headphones/db.py b/headphones/db.py index 32de8a36..20113a1c 100644 --- a/headphones/db.py +++ b/headphones/db.py @@ -15,70 +15,70 @@ db_lock = threading.Lock() def dbFilename(filename="headphones.db"): - return os.path.join(headphones.DATA_DIR, filename) + return os.path.join(headphones.DATA_DIR, filename) class DBConnection: - def __init__(self, filename="headphones.db"): - - self.filename = filename - self.connection = sqlite3.connect(dbFilename(filename), timeout=20) - self.connection.row_factory = sqlite3.Row - - def action(self, query, args=None): - - with db_lock: + def __init__(self, filename="headphones.db"): + + self.filename = filename + self.connection = sqlite3.connect(dbFilename(filename), timeout=20) + self.connection.row_factory = sqlite3.Row + + def action(self, query, args=None): + + with db_lock: - if query == None: - return - - sqlResult = None - attempt = 0 - - while attempt < 5: - try: - if args == None: - #logger.debug(self.filename+": "+query) - sqlResult = self.connection.execute(query) - else: - #logger.debug(self.filename+": "+query+" with args "+str(args)) - sqlResult = self.connection.execute(query, args) - self.connection.commit() - break - except sqlite3.OperationalError, e: - if "unable to open database file" in e.message or "database is locked" in e.message: - logger.warn('Database Error: %s' % e) - attempt += 1 - time.sleep(1) - else: - logger.error('Database error: %s' % e) - raise - except sqlite3.DatabaseError, e: - logger.error('Fatal Error executing %s :: %s' % (query, e)) - raise - - return sqlResult - - def select(self, query, args=None): - - sqlResults = self.action(query, args).fetchall() - - if sqlResults == None: - return [] - - return sqlResults - - def upsert(self, tableName, valueDict, keyDict): - - changesBefore = self.connection.total_changes - - genParams = lambda myDict : [x + " = ?" for x in myDict.keys()] - - query = "UPDATE "+tableName+" SET " + ", ".join(genParams(valueDict)) + " WHERE " + " AND ".join(genParams(keyDict)) - - self.action(query, valueDict.values() + keyDict.values()) - - if self.connection.total_changes == changesBefore: - query = "INSERT INTO "+tableName+" (" + ", ".join(valueDict.keys() + keyDict.keys()) + ")" + \ - " VALUES (" + ", ".join(["?"] * len(valueDict.keys() + keyDict.keys())) + ")" - self.action(query, valueDict.values() + keyDict.values()) \ No newline at end of file + if query == None: + return + + sqlResult = None + attempt = 0 + + while attempt < 5: + try: + if args == None: + #logger.debug(self.filename+": "+query) + sqlResult = self.connection.execute(query) + else: + #logger.debug(self.filename+": "+query+" with args "+str(args)) + sqlResult = self.connection.execute(query, args) + self.connection.commit() + break + except sqlite3.OperationalError, e: + if "unable to open database file" in e.message or "database is locked" in e.message: + logger.warn('Database Error: %s' % e) + attempt += 1 + time.sleep(1) + else: + logger.error('Database error: %s' % e) + raise + except sqlite3.DatabaseError, e: + logger.error('Fatal Error executing %s :: %s' % (query, e)) + raise + + return sqlResult + + def select(self, query, args=None): + + sqlResults = self.action(query, args).fetchall() + + if sqlResults == None: + return [] + + return sqlResults + + def upsert(self, tableName, valueDict, keyDict): + + changesBefore = self.connection.total_changes + + genParams = lambda myDict : [x + " = ?" for x in myDict.keys()] + + query = "UPDATE "+tableName+" SET " + ", ".join(genParams(valueDict)) + " WHERE " + " AND ".join(genParams(keyDict)) + + self.action(query, valueDict.values() + keyDict.values()) + + if self.connection.total_changes == changesBefore: + query = "INSERT INTO "+tableName+" (" + ", ".join(valueDict.keys() + keyDict.keys()) + ")" + \ + " VALUES (" + ", ".join(["?"] * len(valueDict.keys() + keyDict.keys())) + ")" + self.action(query, valueDict.values() + keyDict.values()) diff --git a/headphones/helpers.py b/headphones/helpers.py index 73054bdb..a6d732f2 100644 --- a/headphones/helpers.py +++ b/headphones/helpers.py @@ -20,120 +20,120 @@ def multikeysort(items, columns): return sorted(items, cmp=comparer) def checked(variable): - if variable: - return 'Checked' - else: - return '' - + if variable: + return 'Checked' + else: + return '' + def radio(variable, pos): - if variable == pos: - return 'Checked' - else: - return '' - + if variable == pos: + return 'Checked' + else: + return '' + def latinToAscii(unicrap): - """ - From couch potato - """ - xlate = {0xc0:'A', 0xc1:'A', 0xc2:'A', 0xc3:'A', 0xc4:'A', 0xc5:'A', - 0xc6:'Ae', 0xc7:'C', - 0xc8:'E', 0xc9:'E', 0xca:'E', 0xcb:'E', 0x86:'e', - 0xcc:'I', 0xcd:'I', 0xce:'I', 0xcf:'I', - 0xd0:'Th', 0xd1:'N', - 0xd2:'O', 0xd3:'O', 0xd4:'O', 0xd5:'O', 0xd6:'O', 0xd8:'O', - 0xd9:'U', 0xda:'U', 0xdb:'U', 0xdc:'U', - 0xdd:'Y', 0xde:'th', 0xdf:'ss', - 0xe0:'a', 0xe1:'a', 0xe2:'a', 0xe3:'a', 0xe4:'a', 0xe5:'a', - 0xe6:'ae', 0xe7:'c', - 0xe8:'e', 0xe9:'e', 0xea:'e', 0xeb:'e', 0x0259:'e', - 0xec:'i', 0xed:'i', 0xee:'i', 0xef:'i', - 0xf0:'th', 0xf1:'n', - 0xf2:'o', 0xf3:'o', 0xf4:'o', 0xf5:'o', 0xf6:'o', 0xf8:'o', - 0xf9:'u', 0xfa:'u', 0xfb:'u', 0xfc:'u', - 0xfd:'y', 0xfe:'th', 0xff:'y', - 0xa1:'!', 0xa2:'{cent}', 0xa3:'{pound}', 0xa4:'{currency}', - 0xa5:'{yen}', 0xa6:'|', 0xa7:'{section}', 0xa8:'{umlaut}', - 0xa9:'{C}', 0xaa:'{^a}', 0xab:'<<', 0xac:'{not}', - 0xad:'-', 0xae:'{R}', 0xaf:'_', 0xb0:'{degrees}', - 0xb1:'{+/-}', 0xb2:'{^2}', 0xb3:'{^3}', 0xb4:"'", - 0xb5:'{micro}', 0xb6:'{paragraph}', 0xb7:'*', 0xb8:'{cedilla}', - 0xb9:'{^1}', 0xba:'{^o}', 0xbb:'>>', - 0xbc:'{1/4}', 0xbd:'{1/2}', 0xbe:'{3/4}', 0xbf:'?', - 0xd7:'*', 0xf7:'/' - } + """ + From couch potato + """ + xlate = {0xc0:'A', 0xc1:'A', 0xc2:'A', 0xc3:'A', 0xc4:'A', 0xc5:'A', + 0xc6:'Ae', 0xc7:'C', + 0xc8:'E', 0xc9:'E', 0xca:'E', 0xcb:'E', 0x86:'e', + 0xcc:'I', 0xcd:'I', 0xce:'I', 0xcf:'I', + 0xd0:'Th', 0xd1:'N', + 0xd2:'O', 0xd3:'O', 0xd4:'O', 0xd5:'O', 0xd6:'O', 0xd8:'O', + 0xd9:'U', 0xda:'U', 0xdb:'U', 0xdc:'U', + 0xdd:'Y', 0xde:'th', 0xdf:'ss', + 0xe0:'a', 0xe1:'a', 0xe2:'a', 0xe3:'a', 0xe4:'a', 0xe5:'a', + 0xe6:'ae', 0xe7:'c', + 0xe8:'e', 0xe9:'e', 0xea:'e', 0xeb:'e', 0x0259:'e', + 0xec:'i', 0xed:'i', 0xee:'i', 0xef:'i', + 0xf0:'th', 0xf1:'n', + 0xf2:'o', 0xf3:'o', 0xf4:'o', 0xf5:'o', 0xf6:'o', 0xf8:'o', + 0xf9:'u', 0xfa:'u', 0xfb:'u', 0xfc:'u', + 0xfd:'y', 0xfe:'th', 0xff:'y', + 0xa1:'!', 0xa2:'{cent}', 0xa3:'{pound}', 0xa4:'{currency}', + 0xa5:'{yen}', 0xa6:'|', 0xa7:'{section}', 0xa8:'{umlaut}', + 0xa9:'{C}', 0xaa:'{^a}', 0xab:'<<', 0xac:'{not}', + 0xad:'-', 0xae:'{R}', 0xaf:'_', 0xb0:'{degrees}', + 0xb1:'{+/-}', 0xb2:'{^2}', 0xb3:'{^3}', 0xb4:"'", + 0xb5:'{micro}', 0xb6:'{paragraph}', 0xb7:'*', 0xb8:'{cedilla}', + 0xb9:'{^1}', 0xba:'{^o}', 0xbb:'>>', + 0xbc:'{1/4}', 0xbd:'{1/2}', 0xbe:'{3/4}', 0xbf:'?', + 0xd7:'*', 0xf7:'/' + } - r = '' - for i in unicrap: - if xlate.has_key(ord(i)): - r += xlate[ord(i)] - elif ord(i) >= 0x80: - pass - else: - r += str(i) - return r - + r = '' + for i in unicrap: + if xlate.has_key(ord(i)): + r += xlate[ord(i)] + elif ord(i) >= 0x80: + pass + else: + r += str(i) + return r + def convert_milliseconds(ms): - seconds = ms/1000 - gmtime = time.gmtime(seconds) - if seconds > 3600: - minutes = time.strftime("%H:%M:%S", gmtime) - else: - minutes = time.strftime("%M:%S", gmtime) + seconds = ms/1000 + gmtime = time.gmtime(seconds) + if seconds > 3600: + minutes = time.strftime("%H:%M:%S", gmtime) + else: + minutes = time.strftime("%M:%S", gmtime) - return minutes - + return minutes + def convert_seconds(s): - gmtime = time.gmtime(s) - if s > 3600: - minutes = time.strftime("%H:%M:%S", gmtime) - else: - minutes = time.strftime("%M:%S", gmtime) + gmtime = time.gmtime(s) + if s > 3600: + minutes = time.strftime("%H:%M:%S", gmtime) + else: + minutes = time.strftime("%M:%S", gmtime) - return minutes - + return minutes + def today(): - today = datetime.date.today() - yyyymmdd = datetime.date.isoformat(today) - return yyyymmdd - + today = datetime.date.today() + yyyymmdd = datetime.date.isoformat(today) + return yyyymmdd + def now(): - now = datetime.datetime.now() - return now.strftime("%Y-%m-%d %H:%M:%S") - + now = datetime.datetime.now() + return now.strftime("%Y-%m-%d %H:%M:%S") + def bytes_to_mb(bytes): - mb = int(bytes)/1048576 - size = '%.1f MB' % mb - return size - + mb = int(bytes)/1048576 + size = '%.1f MB' % mb + return size + def replace_all(text, dic): - for i, j in dic.iteritems(): - text = text.replace(i, j) - return text - + for i, j in dic.iteritems(): + text = text.replace(i, j) + return text + def cleanName(string): - pass1 = latinToAscii(string).lower() - out_string = re.sub('[\.\-\/\!\@\#\$\%\^\&\*\(\)\+\-\"\'\,\;\:\[\]\{\}\<\>\=\_]', '', pass1).encode('utf-8') - - return out_string - + pass1 = latinToAscii(string).lower() + out_string = re.sub('[\.\-\/\!\@\#\$\%\^\&\*\(\)\+\-\"\'\,\;\:\[\]\{\}\<\>\=\_]', '', pass1).encode('utf-8') + + return out_string + def cleanTitle(title): - title = re.sub('[\.\-\/\_]', ' ', title).lower() - - # Strip out extra whitespace - title = ' '.join(title.split()) - - title = title.title() - - return title - + title = re.sub('[\.\-\/\_]', ' ', title).lower() + + # Strip out extra whitespace + title = ' '.join(title.split()) + + title = title.title() + + return title + def extract_data(s): - + from headphones import logger #headphones default format @@ -161,18 +161,18 @@ def extract_data(s): return (name, album, year) def extract_logline(s): - # Default log format - pattern = re.compile(r'(?P.*?)\s\-\s(?P.*?)\s*\:\:\s(?P.*?)\s\:\s(?P.*)', re.VERBOSE) - match = pattern.match(s) - if match: - timestamp = match.group("timestamp") - level = match.group("level") - thread = match.group("thread") - message = match.group("message") - return (timestamp, level, thread, message) - else: - return None - + # Default log format + pattern = re.compile(r'(?P.*?)\s\-\s(?P.*?)\s*\:\:\s(?P.*?)\s\:\s(?P.*)', re.VERBOSE) + match = pattern.match(s) + if match: + timestamp = match.group("timestamp") + level = match.group("level") + thread = match.group("thread") + message = match.group("message") + return (timestamp, level, thread, message) + else: + return None + def extract_song_data(s): #headphones default format @@ -202,4 +202,4 @@ def extract_song_data(s): return (name, album, year) else: logger.info("Couldn't parse " + s + " into a valid Newbin format") - return (name, album, year) \ No newline at end of file + return (name, album, year) diff --git a/headphones/importer.py b/headphones/importer.py index dd6a896a..575b5ca4 100644 --- a/headphones/importer.py +++ b/headphones/importer.py @@ -7,369 +7,369 @@ import headphones from headphones import logger, helpers, db, mb, albumart, lastfm various_artists_mbid = '89ad4ac3-39f7-470e-963a-56509c546377' - + def is_exists(artistid): - myDB = db.DBConnection() - - # See if the artist is already in the database - artistlist = myDB.select('SELECT ArtistID, ArtistName from artists WHERE ArtistID=?', [artistid]) + myDB = db.DBConnection() + + # See if the artist is already in the database + artistlist = myDB.select('SELECT ArtistID, ArtistName from artists WHERE ArtistID=?', [artistid]) - if any(artistid in x for x in artistlist): - logger.info(artistlist[0][1] + u" is already in the database. Updating 'have tracks', but not artist information") - return True - else: - return False + if any(artistid in x for x in artistlist): + logger.info(artistlist[0][1] + u" is already in the database. Updating 'have tracks', but not artist information") + return True + else: + return False def artistlist_to_mbids(artistlist, forced=False): - for artist in artistlist: - - if forced: - artist = unicode(artist, 'utf-8') - - results = mb.findArtist(artist, limit=1) - - if not results: - logger.info('No results found for: %s' % artist) - continue - - try: - artistid = results[0]['id'] - - except IndexError: - logger.info('MusicBrainz query turned up no matches for: %s' % artist) - continue - - # Add to database if it doesn't exist - if artistid != various_artists_mbid and not is_exists(artistid): - addArtisttoDB(artistid) - - # Just update the tracks if it does - else: - myDB = db.DBConnection() - havetracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID=?', [artistid])) + len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ?', [artist])) - myDB.action('UPDATE artists SET HaveTracks=? WHERE ArtistID=?', [havetracks, artistid]) - - # Update the similar artist tag cloud: - logger.info('Updating artist information from Last.fm') - try: - lastfm.getSimilar() - except Exception, e: - logger.warn('Failed to update arist information from Last.fm: %s' % e) - + for artist in artistlist: + + if forced: + artist = unicode(artist, 'utf-8') + + results = mb.findArtist(artist, limit=1) + + if not results: + logger.info('No results found for: %s' % artist) + continue + + try: + artistid = results[0]['id'] + + except IndexError: + logger.info('MusicBrainz query turned up no matches for: %s' % artist) + continue + + # Add to database if it doesn't exist + if artistid != various_artists_mbid and not is_exists(artistid): + addArtisttoDB(artistid) + + # Just update the tracks if it does + else: + myDB = db.DBConnection() + havetracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID=?', [artistid])) + len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ?', [artist])) + myDB.action('UPDATE artists SET HaveTracks=? WHERE ArtistID=?', [havetracks, artistid]) + + # Update the similar artist tag cloud: + logger.info('Updating artist information from Last.fm') + try: + lastfm.getSimilar() + except Exception, e: + logger.warn('Failed to update arist information from Last.fm: %s' % e) + def addArtistIDListToDB(artistidlist): - # Used to add a list of artist IDs to the database in a single thread - logger.debug("Importer: Adding artist ids %s" % artistidlist) - for artistid in artistidlist: - addArtisttoDB(artistid) + # Used to add a list of artist IDs to the database in a single thread + logger.debug("Importer: Adding artist ids %s" % artistidlist) + for artistid in artistidlist: + addArtisttoDB(artistid) def addArtisttoDB(artistid, extrasonly=False): - - # Can't add various artists - throws an error from MB - if artistid == various_artists_mbid: - logger.warn('Cannot import Various Artists.') - return - - myDB = db.DBConnection() + + # Can't add various artists - throws an error from MB + if artistid == various_artists_mbid: + logger.warn('Cannot import Various Artists.') + return + + myDB = db.DBConnection() - # We need the current minimal info in the database instantly - # so we don't throw a 500 error when we redirect to the artistPage + # We need the current minimal info in the database instantly + # so we don't throw a 500 error when we redirect to the artistPage - controlValueDict = {"ArtistID": artistid} + controlValueDict = {"ArtistID": artistid} - # Don't replace a known artist name with an "Artist ID" placeholder + # Don't replace a known artist name with an "Artist ID" placeholder - dbartist = myDB.action('SELECT * FROM artists WHERE ArtistID=?', [artistid]).fetchone() - if dbartist is None: - newValueDict = {"ArtistName": "Artist ID: %s" % (artistid), - "Status": "Loading"} - else: - newValueDict = {"Status": "Loading"} + dbartist = myDB.action('SELECT * FROM artists WHERE ArtistID=?', [artistid]).fetchone() + if dbartist is None: + newValueDict = {"ArtistName": "Artist ID: %s" % (artistid), + "Status": "Loading"} + else: + newValueDict = {"Status": "Loading"} - myDB.upsert("artists", newValueDict, controlValueDict) - - artist = mb.getArtist(artistid, extrasonly) - - if not artist: - logger.warn("Error fetching artist info. ID: " + artistid) - if dbartist is None: - newValueDict = {"ArtistName": "Fetch failed, try refreshing. (%s)" % (artistid), - "Status": "Active"} - else: - newValueDict = {"Status": "Active"} - myDB.upsert("artists", newValueDict, controlValueDict) - return - - if artist['artist_name'].startswith('The '): - sortname = artist['artist_name'][4:] - else: - sortname = artist['artist_name'] - + myDB.upsert("artists", newValueDict, controlValueDict) + + artist = mb.getArtist(artistid, extrasonly) + + if not artist: + logger.warn("Error fetching artist info. ID: " + artistid) + if dbartist is None: + newValueDict = {"ArtistName": "Fetch failed, try refreshing. (%s)" % (artistid), + "Status": "Active"} + else: + newValueDict = {"Status": "Active"} + myDB.upsert("artists", newValueDict, controlValueDict) + return + + if artist['artist_name'].startswith('The '): + sortname = artist['artist_name'][4:] + else: + sortname = artist['artist_name'] + - logger.info(u"Now adding/updating: " + artist['artist_name']) - controlValueDict = {"ArtistID": artistid} - newValueDict = {"ArtistName": artist['artist_name'], - "ArtistSortName": sortname, - "DateAdded": helpers.today(), - "Status": "Loading"} - - if headphones.INCLUDE_EXTRAS: - newValueDict['IncludeExtras'] = 1 - - myDB.upsert("artists", newValueDict, controlValueDict) + logger.info(u"Now adding/updating: " + artist['artist_name']) + controlValueDict = {"ArtistID": artistid} + newValueDict = {"ArtistName": artist['artist_name'], + "ArtistSortName": sortname, + "DateAdded": helpers.today(), + "Status": "Loading"} + + if headphones.INCLUDE_EXTRAS: + newValueDict['IncludeExtras'] = 1 + + myDB.upsert("artists", newValueDict, controlValueDict) - for rg in artist['releasegroups']: - - rgid = rg['id'] - - # check if the album already exists - rg_exists = myDB.select("SELECT * from albums WHERE AlbumID=?", [rg['id']]) - - try: - release_dict = mb.getReleaseGroup(rgid) - except Exception, e: - logger.info('Unable to get release information for %s - there may not be any official releases in this release group' % rg['title']) - continue - - if not release_dict: - continue - - logger.info(u"Now adding/updating album: " + rg['title']) - controlValueDict = {"AlbumID": rg['id']} - - if len(rg_exists): - - newValueDict = {"AlbumASIN": release_dict['asin'], - "ReleaseDate": release_dict['releasedate'], - } - - else: - - newValueDict = {"ArtistID": artistid, - "ArtistName": artist['artist_name'], - "AlbumTitle": rg['title'], - "AlbumASIN": release_dict['asin'], - "ReleaseDate": release_dict['releasedate'], - "DateAdded": helpers.today(), - "Type": rg['type'] - } - - if headphones.AUTOWANT_ALL: - newValueDict['Status'] = "Wanted" - elif release_dict['releasedate'] > helpers.today() and headphones.AUTOWANT_UPCOMING: - newValueDict['Status'] = "Wanted" - else: - newValueDict['Status'] = "Skipped" - - myDB.upsert("albums", newValueDict, controlValueDict) - - try: - lastfm.getAlbumDescription(rg['id'], artist['artist_name'], rg['title']) - except Exception, e: - logger.error('Attempt to retrieve album description from Last.fm failed: %s' % e) - - # I changed the albumid from releaseid -> rgid, so might need to delete albums that have a releaseid - for release in release_dict['releaselist']: - myDB.action('DELETE from albums WHERE AlbumID=?', [release['releaseid']]) - myDB.action('DELETE from tracks WHERE AlbumID=?', [release['releaseid']]) - - for track in release_dict['tracks']: - - cleanname = helpers.cleanName(artist['artist_name'] + ' ' + rg['title'] + ' ' + track['title']) - - controlValueDict = {"TrackID": track['id'], - "AlbumID": rg['id']} - newValueDict = {"ArtistID": artistid, - "ArtistName": artist['artist_name'], - "AlbumTitle": rg['title'], - "AlbumASIN": release_dict['asin'], - "TrackTitle": track['title'], - "TrackDuration": track['duration'], - "TrackNumber": track['number'], - "CleanName": cleanname - } - - match = myDB.action('SELECT Location, BitRate, Format from have WHERE CleanName=?', [cleanname]).fetchone() - - if not match: - match = myDB.action('SELECT Location, BitRate, Format from have WHERE ArtistName LIKE ? AND AlbumTitle LIKE ? AND TrackTitle LIKE ?', [artist['artist_name'], rg['title'], track['title']]).fetchone() - if not match: - match = myDB.action('SELECT Location, BitRate, Format from have WHERE TrackID=?', [track['id']]).fetchone() - if match: - newValueDict['Location'] = match['Location'] - newValueDict['BitRate'] = match['BitRate'] - newValueDict['Format'] = match['Format'] - myDB.action('DELETE from have WHERE Location=?', [match['Location']]) - - myDB.upsert("tracks", newValueDict, controlValueDict) - - latestalbum = myDB.action('SELECT AlbumTitle, ReleaseDate, AlbumID from albums WHERE ArtistID=? order by ReleaseDate DESC', [artistid]).fetchone() - totaltracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID=?', [artistid])) - havetracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID=? AND Location IS NOT NULL', [artistid])) + len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ?', [artist['artist_name']])) + for rg in artist['releasegroups']: + + rgid = rg['id'] + + # check if the album already exists + rg_exists = myDB.select("SELECT * from albums WHERE AlbumID=?", [rg['id']]) + + try: + release_dict = mb.getReleaseGroup(rgid) + except Exception, e: + logger.info('Unable to get release information for %s - there may not be any official releases in this release group' % rg['title']) + continue + + if not release_dict: + continue + + logger.info(u"Now adding/updating album: " + rg['title']) + controlValueDict = {"AlbumID": rg['id']} + + if len(rg_exists): + + newValueDict = {"AlbumASIN": release_dict['asin'], + "ReleaseDate": release_dict['releasedate'], + } + + else: + + newValueDict = {"ArtistID": artistid, + "ArtistName": artist['artist_name'], + "AlbumTitle": rg['title'], + "AlbumASIN": release_dict['asin'], + "ReleaseDate": release_dict['releasedate'], + "DateAdded": helpers.today(), + "Type": rg['type'] + } + + if headphones.AUTOWANT_ALL: + newValueDict['Status'] = "Wanted" + elif release_dict['releasedate'] > helpers.today() and headphones.AUTOWANT_UPCOMING: + newValueDict['Status'] = "Wanted" + else: + newValueDict['Status'] = "Skipped" + + myDB.upsert("albums", newValueDict, controlValueDict) + + try: + lastfm.getAlbumDescription(rg['id'], artist['artist_name'], rg['title']) + except Exception, e: + logger.error('Attempt to retrieve album description from Last.fm failed: %s' % e) + + # I changed the albumid from releaseid -> rgid, so might need to delete albums that have a releaseid + for release in release_dict['releaselist']: + myDB.action('DELETE from albums WHERE AlbumID=?', [release['releaseid']]) + myDB.action('DELETE from tracks WHERE AlbumID=?', [release['releaseid']]) + + for track in release_dict['tracks']: + + cleanname = helpers.cleanName(artist['artist_name'] + ' ' + rg['title'] + ' ' + track['title']) + + controlValueDict = {"TrackID": track['id'], + "AlbumID": rg['id']} + newValueDict = {"ArtistID": artistid, + "ArtistName": artist['artist_name'], + "AlbumTitle": rg['title'], + "AlbumASIN": release_dict['asin'], + "TrackTitle": track['title'], + "TrackDuration": track['duration'], + "TrackNumber": track['number'], + "CleanName": cleanname + } + + match = myDB.action('SELECT Location, BitRate, Format from have WHERE CleanName=?', [cleanname]).fetchone() + + if not match: + match = myDB.action('SELECT Location, BitRate, Format from have WHERE ArtistName LIKE ? AND AlbumTitle LIKE ? AND TrackTitle LIKE ?', [artist['artist_name'], rg['title'], track['title']]).fetchone() + if not match: + match = myDB.action('SELECT Location, BitRate, Format from have WHERE TrackID=?', [track['id']]).fetchone() + if match: + newValueDict['Location'] = match['Location'] + newValueDict['BitRate'] = match['BitRate'] + newValueDict['Format'] = match['Format'] + myDB.action('DELETE from have WHERE Location=?', [match['Location']]) + + myDB.upsert("tracks", newValueDict, controlValueDict) + + latestalbum = myDB.action('SELECT AlbumTitle, ReleaseDate, AlbumID from albums WHERE ArtistID=? order by ReleaseDate DESC', [artistid]).fetchone() + totaltracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID=?', [artistid])) + havetracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID=? AND Location IS NOT NULL', [artistid])) + len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ?', [artist['artist_name']])) - controlValueDict = {"ArtistID": artistid} - - if latestalbum: - newValueDict = {"Status": "Active", - "LatestAlbum": latestalbum['AlbumTitle'], - "ReleaseDate": latestalbum['ReleaseDate'], - "AlbumID": latestalbum['AlbumID'], - "TotalTracks": totaltracks, - "HaveTracks": havetracks} - else: - newValueDict = {"Status": "Active", - "TotalTracks": totaltracks, - "HaveTracks": havetracks} - - newValueDict['LastUpdated'] = helpers.now() - - myDB.upsert("artists", newValueDict, controlValueDict) - logger.info(u"Updating complete for: " + artist['artist_name']) - + controlValueDict = {"ArtistID": artistid} + + if latestalbum: + newValueDict = {"Status": "Active", + "LatestAlbum": latestalbum['AlbumTitle'], + "ReleaseDate": latestalbum['ReleaseDate'], + "AlbumID": latestalbum['AlbumID'], + "TotalTracks": totaltracks, + "HaveTracks": havetracks} + else: + newValueDict = {"Status": "Active", + "TotalTracks": totaltracks, + "HaveTracks": havetracks} + + newValueDict['LastUpdated'] = helpers.now() + + myDB.upsert("artists", newValueDict, controlValueDict) + logger.info(u"Updating complete for: " + artist['artist_name']) + def addReleaseById(rid): - - myDB = db.DBConnection() + + myDB = db.DBConnection() - rgid = None - artistid = None - release_dict = None - results = myDB.select("SELECT albums.ArtistID, releases.ReleaseGroupID from releases, albums WHERE releases.ReleaseID=? and releases.ReleaseGroupID=albums.AlbumID LIMIT 1", [rid]) - for result in results: - rgid = result['ReleaseGroupID'] - artistid = result['ArtistID'] - logger.debug("Found a cached releaseid : releasegroupid relationship: " + rid + " : " + rgid) - if not rgid: - #didn't find it in the cache, get the information from MB - logger.debug("Didn't find releaseID " + rid + " in the cache. Looking up its ReleaseGroupID") - try: - release_dict = mb.getRelease(rid) - except Exception, e: - logger.info('Unable to get release information for Release: ' + str(rid) + " " + str(e)) - return - if not release_dict: - logger.info('Unable to get release information for Release: ' + str(rid) + " no dict") - return - - rgid = release_dict['rgid'] - artistid = release_dict['artist_id'] - - #we don't want to make more calls to MB here unless we have to, could be happening quite a lot - rg_exists = myDB.select("SELECT * from albums WHERE AlbumID=?", [rgid]) - - #make sure the artist exists since I don't know what happens later if it doesn't - artist_exists = myDB.select("SELECT * from artists WHERE ArtistID=?", [artistid]) - - if not artist_exists and release_dict: - if release_dict['artist_name'].startswith('The '): - sortname = release_dict['artist_name'][4:] - else: - sortname = release_dict['artist_name'] - - - logger.info(u"Now manually adding: " + release_dict['artist_name'] + " - with status Paused") - controlValueDict = {"ArtistID": release_dict['artist_id']} - newValueDict = {"ArtistName": release_dict['artist_name'], - "ArtistSortName": sortname, - "DateAdded": helpers.today(), - "Status": "Paused"} - - if headphones.INCLUDE_EXTRAS: - newValueDict['IncludeExtras'] = 1 - - myDB.upsert("artists", newValueDict, controlValueDict) - - elif not artist_exists and not release_dict: - logger.error("Artist does not exist in the database and did not get a valid response from MB. Skipping release.") - return - - if not rg_exists and release_dict: #it should never be the case that we have an rg and not the artist - #but if it is this will fail - logger.info(u"Now adding-by-id album (" + release_dict['title'] + ") from id: " + rgid) - controlValueDict = {"AlbumID": rgid} + rgid = None + artistid = None + release_dict = None + results = myDB.select("SELECT albums.ArtistID, releases.ReleaseGroupID from releases, albums WHERE releases.ReleaseID=? and releases.ReleaseGroupID=albums.AlbumID LIMIT 1", [rid]) + for result in results: + rgid = result['ReleaseGroupID'] + artistid = result['ArtistID'] + logger.debug("Found a cached releaseid : releasegroupid relationship: " + rid + " : " + rgid) + if not rgid: + #didn't find it in the cache, get the information from MB + logger.debug("Didn't find releaseID " + rid + " in the cache. Looking up its ReleaseGroupID") + try: + release_dict = mb.getRelease(rid) + except Exception, e: + logger.info('Unable to get release information for Release: ' + str(rid) + " " + str(e)) + return + if not release_dict: + logger.info('Unable to get release information for Release: ' + str(rid) + " no dict") + return + + rgid = release_dict['rgid'] + artistid = release_dict['artist_id'] + + #we don't want to make more calls to MB here unless we have to, could be happening quite a lot + rg_exists = myDB.select("SELECT * from albums WHERE AlbumID=?", [rgid]) + + #make sure the artist exists since I don't know what happens later if it doesn't + artist_exists = myDB.select("SELECT * from artists WHERE ArtistID=?", [artistid]) + + if not artist_exists and release_dict: + if release_dict['artist_name'].startswith('The '): + sortname = release_dict['artist_name'][4:] + else: + sortname = release_dict['artist_name'] + + + logger.info(u"Now manually adding: " + release_dict['artist_name'] + " - with status Paused") + controlValueDict = {"ArtistID": release_dict['artist_id']} + newValueDict = {"ArtistName": release_dict['artist_name'], + "ArtistSortName": sortname, + "DateAdded": helpers.today(), + "Status": "Paused"} + + if headphones.INCLUDE_EXTRAS: + newValueDict['IncludeExtras'] = 1 + + myDB.upsert("artists", newValueDict, controlValueDict) + + elif not artist_exists and not release_dict: + logger.error("Artist does not exist in the database and did not get a valid response from MB. Skipping release.") + return + + if not rg_exists and release_dict: #it should never be the case that we have an rg and not the artist + #but if it is this will fail + logger.info(u"Now adding-by-id album (" + release_dict['title'] + ") from id: " + rgid) + controlValueDict = {"AlbumID": rgid} - newValueDict = {"ArtistID": release_dict['artist_id'], - "ArtistName": release_dict['artist_name'], - "AlbumTitle": release_dict['rg_title'], - "AlbumASIN": release_dict['asin'], - "ReleaseDate": release_dict['date'], - "DateAdded": helpers.today(), - "Status": 'Wanted', - "Type": release_dict['rg_type'] - } - - myDB.upsert("albums", newValueDict, controlValueDict) + newValueDict = {"ArtistID": release_dict['artist_id'], + "ArtistName": release_dict['artist_name'], + "AlbumTitle": release_dict['rg_title'], + "AlbumASIN": release_dict['asin'], + "ReleaseDate": release_dict['date'], + "DateAdded": helpers.today(), + "Status": 'Wanted', + "Type": release_dict['rg_type'] + } + + myDB.upsert("albums", newValueDict, controlValueDict) - #keep a local cache of these so that external programs that are adding releasesByID don't hammer MB - myDB.action('INSERT INTO releases VALUES( ?, ?)', [rid, release_dict['rgid']]) - - for track in release_dict['tracks']: - - cleanname = helpers.cleanName(release_dict['artist_name'] + ' ' + release_dict['rg_title'] + ' ' + track['title']) - - controlValueDict = {"TrackID": track['id'], - "AlbumID": rgid} - newValueDict = {"ArtistID": release_dict['artist_id'], - "ArtistName": release_dict['artist_name'], - "AlbumTitle": release_dict['rg_title'], - "AlbumASIN": release_dict['asin'], - "TrackTitle": track['title'], - "TrackDuration": track['duration'], - "TrackNumber": track['number'], - "CleanName": cleanname - } - - match = myDB.action('SELECT Location, BitRate, Format from have WHERE CleanName=?', [cleanname]).fetchone() - - if not match: - match = myDB.action('SELECT Location, BitRate, Format from have WHERE ArtistName LIKE ? AND AlbumTitle LIKE ? AND TrackTitle LIKE ?', [release_dict['artist_name'], release_dict['rg_title'], track['title']]).fetchone() - - if not match: - match = myDB.action('SELECT Location, BitRate, Format from have WHERE TrackID=?', [track['id']]).fetchone() - - if match: - newValueDict['Location'] = match['Location'] - newValueDict['BitRate'] = match['BitRate'] - newValueDict['Format'] = match['Format'] - myDB.action('DELETE from have WHERE Location=?', [match['Location']]) - - myDB.upsert("tracks", newValueDict, controlValueDict) - - #start a search for the album - import searcher - searcher.searchNZB(rgid, False) - elif not rg_exists and not release_dict: - logger.error("ReleaseGroup does not exist in the database and did not get a valid response from MB. Skipping release.") - return - else: - logger.info('Release ' + str(rid) + " already exists in the database!") + #keep a local cache of these so that external programs that are adding releasesByID don't hammer MB + myDB.action('INSERT INTO releases VALUES( ?, ?)', [rid, release_dict['rgid']]) + + for track in release_dict['tracks']: + + cleanname = helpers.cleanName(release_dict['artist_name'] + ' ' + release_dict['rg_title'] + ' ' + track['title']) + + controlValueDict = {"TrackID": track['id'], + "AlbumID": rgid} + newValueDict = {"ArtistID": release_dict['artist_id'], + "ArtistName": release_dict['artist_name'], + "AlbumTitle": release_dict['rg_title'], + "AlbumASIN": release_dict['asin'], + "TrackTitle": track['title'], + "TrackDuration": track['duration'], + "TrackNumber": track['number'], + "CleanName": cleanname + } + + match = myDB.action('SELECT Location, BitRate, Format from have WHERE CleanName=?', [cleanname]).fetchone() + + if not match: + match = myDB.action('SELECT Location, BitRate, Format from have WHERE ArtistName LIKE ? AND AlbumTitle LIKE ? AND TrackTitle LIKE ?', [release_dict['artist_name'], release_dict['rg_title'], track['title']]).fetchone() + + if not match: + match = myDB.action('SELECT Location, BitRate, Format from have WHERE TrackID=?', [track['id']]).fetchone() + + if match: + newValueDict['Location'] = match['Location'] + newValueDict['BitRate'] = match['BitRate'] + newValueDict['Format'] = match['Format'] + myDB.action('DELETE from have WHERE Location=?', [match['Location']]) + + myDB.upsert("tracks", newValueDict, controlValueDict) + + #start a search for the album + import searcher + searcher.searchNZB(rgid, False) + elif not rg_exists and not release_dict: + logger.error("ReleaseGroup does not exist in the database and did not get a valid response from MB. Skipping release.") + return + else: + logger.info('Release ' + str(rid) + " already exists in the database!") def updateFormat(): - myDB = db.DBConnection() - tracks = myDB.select('SELECT * from tracks WHERE Location IS NOT NULL and Format IS NULL') - if len(tracks) > 0: - logger.info('Finding media format for %s files' % len(tracks)) - for track in tracks: - try: - f = MediaFile(track['Location']) - except Exception, e: - logger.info("Exception from MediaFile for: " + track['Location'] + " : " + str(e)) - continue - controlValueDict = {"TrackID": track['TrackID']} - newValueDict = {"Format": f.format} - myDB.upsert("tracks", newValueDict, controlValueDict) - logger.info('Finished finding media format for %s files' % len(tracks)) - havetracks = myDB.select('SELECT * from have WHERE Location IS NOT NULL and Format IS NULL') - if len(havetracks) > 0: - logger.info('Finding media format for %s files' % len(havetracks)) - for track in havetracks: - try: - f = MediaFile(track['Location']) - except Exception, e: - logger.info("Exception from MediaFile for: " + track['Location'] + " : " + str(e)) - continue - controlValueDict = {"TrackID": track['TrackID']} - newValueDict = {"Format": f.format} - myDB.upsert("have", newValueDict, controlValueDict) - logger.info('Finished finding media format for %s files' % len(havetracks)) + myDB = db.DBConnection() + tracks = myDB.select('SELECT * from tracks WHERE Location IS NOT NULL and Format IS NULL') + if len(tracks) > 0: + logger.info('Finding media format for %s files' % len(tracks)) + for track in tracks: + try: + f = MediaFile(track['Location']) + except Exception, e: + logger.info("Exception from MediaFile for: " + track['Location'] + " : " + str(e)) + continue + controlValueDict = {"TrackID": track['TrackID']} + newValueDict = {"Format": f.format} + myDB.upsert("tracks", newValueDict, controlValueDict) + logger.info('Finished finding media format for %s files' % len(tracks)) + havetracks = myDB.select('SELECT * from have WHERE Location IS NOT NULL and Format IS NULL') + if len(havetracks) > 0: + logger.info('Finding media format for %s files' % len(havetracks)) + for track in havetracks: + try: + f = MediaFile(track['Location']) + except Exception, e: + logger.info("Exception from MediaFile for: " + track['Location'] + " : " + str(e)) + continue + controlValueDict = {"TrackID": track['TrackID']} + newValueDict = {"Format": f.format} + myDB.upsert("have", newValueDict, controlValueDict) + logger.info('Finished finding media format for %s files' % len(havetracks)) diff --git a/headphones/lastfm.py b/headphones/lastfm.py index f32f9963..84df9050 100644 --- a/headphones/lastfm.py +++ b/headphones/lastfm.py @@ -11,179 +11,179 @@ api_key = '395e6ec6bb557382fc41fde867bce66f' def getSimilar(): - - myDB = db.DBConnection() - results = myDB.select('SELECT ArtistID from artists ORDER BY HaveTracks DESC') - - artistlist = [] - - for result in results[:12]: - - url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&mbid=%s&api_key=%s' % (result['ArtistID'], api_key) - - try: - data = urllib.urlopen(url).read() - except: - time.sleep(1) - continue - - if len(data) < 200: - continue - - d = minidom.parseString(data) - node = d.documentElement - artists = d.getElementsByTagName("artist") - - for artist in artists: - namenode = artist.getElementsByTagName("name")[0].childNodes - mbidnode = artist.getElementsByTagName("mbid")[0].childNodes - - for node in namenode: - artist_name = node.data - for node in mbidnode: - artist_mbid = node.data - - try: - if not any(artist_mbid in x for x in results): - artistlist.append((artist_name, artist_mbid)) - except: - continue - - count = defaultdict(int) - - for artist, mbid in artistlist: - count[artist, mbid] += 1 - - items = count.items() - - top_list = sorted(items, key=lambda x: x[1], reverse=True)[:25] - - random.shuffle(top_list) - - myDB.action('''DELETE from lastfmcloud''') - for tuple in top_list: - artist_name, artist_mbid = tuple[0] - count = tuple[1] - myDB.action('INSERT INTO lastfmcloud VALUES( ?, ?, ?)', [artist_name, artist_mbid, count]) - + + myDB = db.DBConnection() + results = myDB.select('SELECT ArtistID from artists ORDER BY HaveTracks DESC') + + artistlist = [] + + for result in results[:12]: + + url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&mbid=%s&api_key=%s' % (result['ArtistID'], api_key) + + try: + data = urllib.urlopen(url).read() + except: + time.sleep(1) + continue + + if len(data) < 200: + continue + + d = minidom.parseString(data) + node = d.documentElement + artists = d.getElementsByTagName("artist") + + for artist in artists: + namenode = artist.getElementsByTagName("name")[0].childNodes + mbidnode = artist.getElementsByTagName("mbid")[0].childNodes + + for node in namenode: + artist_name = node.data + for node in mbidnode: + artist_mbid = node.data + + try: + if not any(artist_mbid in x for x in results): + artistlist.append((artist_name, artist_mbid)) + except: + continue + + count = defaultdict(int) + + for artist, mbid in artistlist: + count[artist, mbid] += 1 + + items = count.items() + + top_list = sorted(items, key=lambda x: x[1], reverse=True)[:25] + + random.shuffle(top_list) + + myDB.action('''DELETE from lastfmcloud''') + for tuple in top_list: + artist_name, artist_mbid = tuple[0] + count = tuple[1] + myDB.action('INSERT INTO lastfmcloud VALUES( ?, ?, ?)', [artist_name, artist_mbid, count]) + def getArtists(): - myDB = db.DBConnection() - results = myDB.select('SELECT ArtistID from artists') + myDB = db.DBConnection() + results = myDB.select('SELECT ArtistID from artists') - if not headphones.LASTFM_USERNAME: - return - - else: - username = headphones.LASTFM_USERNAME - - url = 'http://ws.audioscrobbler.com/2.0/?method=library.getartists&limit=10000&api_key=%s&user=%s' % (api_key, username) - data = urllib.urlopen(url).read() - d = minidom.parseString(data) - artists = d.getElementsByTagName("artist") - - artistlist = [] - - for artist in artists: - mbidnode = artist.getElementsByTagName("mbid")[0].childNodes + if not headphones.LASTFM_USERNAME: + return + + else: + username = headphones.LASTFM_USERNAME + + url = 'http://ws.audioscrobbler.com/2.0/?method=library.getartists&limit=10000&api_key=%s&user=%s' % (api_key, username) + data = urllib.urlopen(url).read() + d = minidom.parseString(data) + artists = d.getElementsByTagName("artist") + + artistlist = [] + + for artist in artists: + mbidnode = artist.getElementsByTagName("mbid")[0].childNodes - for node in mbidnode: - artist_mbid = node.data - - try: - if not any(artist_mbid in x for x in results): - artistlist.append(artist_mbid) - except: - continue - - from headphones import importer - - for artistid in artistlist: - importer.addArtisttoDB(artistid) - + for node in mbidnode: + artist_mbid = node.data + + try: + if not any(artist_mbid in x for x in results): + artistlist.append(artist_mbid) + except: + continue + + from headphones import importer + + for artistid in artistlist: + importer.addArtisttoDB(artistid) + def getAlbumDescription(rgid, artist, album): - - myDB = db.DBConnection() - result = myDB.select('SELECT Summary from descriptions WHERE ReleaseGroupID=?', [rgid]) - - if result: - return - - params = { "method": 'album.getInfo', - "api_key": api_key, + + myDB = db.DBConnection() + result = myDB.select('SELECT Summary from descriptions WHERE ReleaseGroupID=?', [rgid]) + + if result: + return + + params = { "method": 'album.getInfo', + "api_key": api_key, "artist": artist.encode('utf-8'), "album": album.encode('utf-8') } - searchURL = 'http://ws.audioscrobbler.com/2.0/?' + urllib.urlencode(params) - data = urllib.urlopen(searchURL).read() - - if data == 'Album not found': - return - - try: - d = minidom.parseString(data) + searchURL = 'http://ws.audioscrobbler.com/2.0/?' + urllib.urlencode(params) + data = urllib.urlopen(searchURL).read() + + if data == 'Album not found': + return + + try: + d = minidom.parseString(data) - albuminfo = d.getElementsByTagName("album") - - for item in albuminfo: - summarynode = item.getElementsByTagName("summary")[0].childNodes - contentnode = item.getElementsByTagName("content")[0].childNodes - for node in summarynode: - summary = node.data - for node in contentnode: - content = node.data - - controlValueDict = {'ReleaseGroupID': rgid} - newValueDict = {'Summary': summary, - 'Content': content} - myDB.upsert("descriptions", newValueDict, controlValueDict) - - except: - return + albuminfo = d.getElementsByTagName("album") + + for item in albuminfo: + summarynode = item.getElementsByTagName("summary")[0].childNodes + contentnode = item.getElementsByTagName("content")[0].childNodes + for node in summarynode: + summary = node.data + for node in contentnode: + content = node.data + + controlValueDict = {'ReleaseGroupID': rgid} + newValueDict = {'Summary': summary, + 'Content': content} + myDB.upsert("descriptions", newValueDict, controlValueDict) + + except: + return def getAlbumDescriptionOld(rgid, releaselist): - """ - This was a dumb way to do it - going to just use artist & album name but keeping this here - because I may use it to fetch and cache album art - """ + """ + This was a dumb way to do it - going to just use artist & album name but keeping this here + because I may use it to fetch and cache album art + """ - myDB = db.DBConnection() - result = myDB.select('SELECT Summary from descriptions WHERE ReleaseGroupID=?', [rgid]) - - if result: - return - - for release in releaselist: - - mbid = release['releaseid'] - url = 'http://ws.audioscrobbler.com/2.0/?method=album.getInfo&mbid=%s&api_key=%s' % (mbid, api_key) - data = urllib.urlopen(url).read() - - if data == 'Album not found': - continue - - try: - d = minidom.parseString(data) - - albuminfo = d.getElementsByTagName("album") - - for item in albuminfo: - summarynode = item.getElementsByTagName("summary")[0].childNodes - contentnode = item.getElementsByTagName("content")[0].childNodes - for node in summarynode: - summary = node.data - for node in contentnode: - content = node.data - - controlValueDict = {'ReleaseGroupID': rgid} - newValueDict = {'ReleaseID': mbid, - 'Summary': summary, - 'Content': content} - myDB.upsert("descriptions", newValueDict, controlValueDict) - break - - except: - continue - - \ No newline at end of file + myDB = db.DBConnection() + result = myDB.select('SELECT Summary from descriptions WHERE ReleaseGroupID=?', [rgid]) + + if result: + return + + for release in releaselist: + + mbid = release['releaseid'] + url = 'http://ws.audioscrobbler.com/2.0/?method=album.getInfo&mbid=%s&api_key=%s' % (mbid, api_key) + data = urllib.urlopen(url).read() + + if data == 'Album not found': + continue + + try: + d = minidom.parseString(data) + + albuminfo = d.getElementsByTagName("album") + + for item in albuminfo: + summarynode = item.getElementsByTagName("summary")[0].childNodes + contentnode = item.getElementsByTagName("content")[0].childNodes + for node in summarynode: + summary = node.data + for node in contentnode: + content = node.data + + controlValueDict = {'ReleaseGroupID': rgid} + newValueDict = {'ReleaseID': mbid, + 'Summary': summary, + 'Content': content} + myDB.upsert("descriptions", newValueDict, controlValueDict) + break + + except: + continue + + diff --git a/headphones/librarysync.py b/headphones/librarysync.py index eef8a90c..900cd405 100644 --- a/headphones/librarysync.py +++ b/headphones/librarysync.py @@ -8,212 +8,212 @@ from headphones import db, logger, helpers, importer def libraryScan(dir=None): - if not dir: - dir = headphones.MUSIC_DIR - - try: - dir = str(dir) - except UnicodeEncodeError: - dir = unicode(dir).encode('unicode_escape') - - if not os.path.isdir(dir): - logger.warn('Cannot find directory: %s. Not scanning' % dir) - return + if not dir: + dir = headphones.MUSIC_DIR + + try: + dir = str(dir) + except UnicodeEncodeError: + dir = unicode(dir).encode('unicode_escape') + + if not os.path.isdir(dir): + logger.warn('Cannot find directory: %s. Not scanning' % dir) + return - myDB = db.DBConnection() - - # Clean up bad filepaths - tracks = myDB.select('SELECT Location, TrackID from tracks WHERE Location IS NOT NULL') - - for track in tracks: - if not os.path.isfile(track['Location'].encode(headphones.SYS_ENCODING)): - myDB.action('UPDATE tracks SET Location=?, BitRate=?, Format=? WHERE TrackID=?', [None, None, None, track['TrackID']]) + myDB = db.DBConnection() + + # Clean up bad filepaths + tracks = myDB.select('SELECT Location, TrackID from tracks WHERE Location IS NOT NULL') + + for track in tracks: + if not os.path.isfile(track['Location'].encode(headphones.SYS_ENCODING)): + myDB.action('UPDATE tracks SET Location=?, BitRate=?, Format=? WHERE TrackID=?', [None, None, None, track['TrackID']]) - logger.info('Scanning music directory: %s' % dir) + logger.info('Scanning music directory: %s' % dir) - new_artists = [] - bitrates = [] + new_artists = [] + bitrates = [] - myDB.action('DELETE from have') - - for r,d,f in os.walk(dir): - for files in f: - # MEDIA_FORMATS = music file extensions, e.g. mp3, flac, etc - if any(files.lower().endswith('.' + x.lower()) for x in headphones.MEDIA_FORMATS): + myDB.action('DELETE from have') + + for r,d,f in os.walk(dir): + for files in f: + # MEDIA_FORMATS = music file extensions, e.g. mp3, flac, etc + if any(files.lower().endswith('.' + x.lower()) for x in headphones.MEDIA_FORMATS): - song = os.path.join(r, files) - file = unicode(os.path.join(r, files), headphones.SYS_ENCODING, errors='replace') + song = os.path.join(r, files) + file = unicode(os.path.join(r, files), headphones.SYS_ENCODING, errors='replace') - # Try to read the metadata - try: - f = MediaFile(song) + # Try to read the metadata + try: + f = MediaFile(song) - except: - logger.error('Cannot read file: ' + file) - continue - - # Grab the bitrates for the auto detect bit rate option - if f.bitrate: - bitrates.append(f.bitrate) - - # Try to find a match based on artist/album/tracktitle - if f.albumartist: - f_artist = f.albumartist - elif f.artist: - f_artist = f.artist - else: - continue - - if f_artist and f.album and f.title: + except: + logger.error('Cannot read file: ' + file) + continue + + # Grab the bitrates for the auto detect bit rate option + if f.bitrate: + bitrates.append(f.bitrate) + + # Try to find a match based on artist/album/tracktitle + if f.albumartist: + f_artist = f.albumartist + elif f.artist: + f_artist = f.artist + else: + continue + + if f_artist and f.album and f.title: - track = myDB.action('SELECT TrackID from tracks WHERE CleanName LIKE ?', [helpers.cleanName(f_artist +' '+f.album+' '+f.title)]).fetchone() - - if not track: - track = myDB.action('SELECT TrackID from tracks WHERE ArtistName LIKE ? AND AlbumTitle LIKE ? AND TrackTitle LIKE ?', [f_artist, f.album, f.title]).fetchone() - - if track: - myDB.action('UPDATE tracks SET Location=?, BitRate=?, Format=? WHERE TrackID=?', [file, f.bitrate, f.format, track['TrackID']]) - continue - - # Try to match on mbid if available and we couldn't find a match based on metadata - if f.mb_trackid: + track = myDB.action('SELECT TrackID from tracks WHERE CleanName LIKE ?', [helpers.cleanName(f_artist +' '+f.album+' '+f.title)]).fetchone() + + if not track: + track = myDB.action('SELECT TrackID from tracks WHERE ArtistName LIKE ? AND AlbumTitle LIKE ? AND TrackTitle LIKE ?', [f_artist, f.album, f.title]).fetchone() + + if track: + myDB.action('UPDATE tracks SET Location=?, BitRate=?, Format=? WHERE TrackID=?', [file, f.bitrate, f.format, track['TrackID']]) + continue + + # Try to match on mbid if available and we couldn't find a match based on metadata + if f.mb_trackid: - # Wondering if theres a better way to do this -> do one thing if the row exists, - # do something else if it doesn't - track = myDB.action('SELECT TrackID from tracks WHERE TrackID=?', [f.mb_trackid]).fetchone() - - if track: - myDB.action('UPDATE tracks SET Location=?, BitRate=?, Format=? WHERE TrackID=?', [file, f.bitrate, f.format, track['TrackID']]) - continue - - # if we can't find a match in the database on a track level, it might be a new artist or it might be on a non-mb release - new_artists.append(f_artist) - - # The have table will become the new database for unmatched tracks (i.e. tracks with no associated links in the database - myDB.action('INSERT INTO have (ArtistName, AlbumTitle, TrackNumber, TrackTitle, TrackLength, BitRate, Genre, Date, TrackID, Location, CleanName, Format) VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [f_artist, f.album, f.track, f.title, f.length, f.bitrate, f.genre, f.date, f.mb_trackid, file, helpers.cleanName(f_artist+' '+f.album+' '+f.title), f.format]) + # Wondering if theres a better way to do this -> do one thing if the row exists, + # do something else if it doesn't + track = myDB.action('SELECT TrackID from tracks WHERE TrackID=?', [f.mb_trackid]).fetchone() + + if track: + myDB.action('UPDATE tracks SET Location=?, BitRate=?, Format=? WHERE TrackID=?', [file, f.bitrate, f.format, track['TrackID']]) + continue + + # if we can't find a match in the database on a track level, it might be a new artist or it might be on a non-mb release + new_artists.append(f_artist) + + # The have table will become the new database for unmatched tracks (i.e. tracks with no associated links in the database + myDB.action('INSERT INTO have (ArtistName, AlbumTitle, TrackNumber, TrackTitle, TrackLength, BitRate, Genre, Date, TrackID, Location, CleanName, Format) VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [f_artist, f.album, f.track, f.title, f.length, f.bitrate, f.genre, f.date, f.mb_trackid, file, helpers.cleanName(f_artist+' '+f.album+' '+f.title), f.format]) - logger.info('Completed scanning of directory: %s' % dir) - logger.info('Checking filepaths to see if we can find any matches') + logger.info('Completed scanning of directory: %s' % dir) + logger.info('Checking filepaths to see if we can find any matches') - # Now check empty file paths to see if we can find a match based on their folder format - tracks = myDB.select('SELECT * from tracks WHERE Location IS NULL') - for track in tracks: - - release = myDB.action('SELECT * from albums WHERE AlbumID=?', [track['AlbumID']]).fetchone() + # Now check empty file paths to see if we can find a match based on their folder format + tracks = myDB.select('SELECT * from tracks WHERE Location IS NULL') + for track in tracks: + + release = myDB.action('SELECT * from albums WHERE AlbumID=?', [track['AlbumID']]).fetchone() - try: - year = release['ReleaseDate'][:4] - except TypeError: - year = '' - - artist = release['ArtistName'].replace('/', '_') - album = release['AlbumTitle'].replace('/', '_') - releasetype = release['Type'].replace('/', '_') - - if release['ArtistName'].startswith('The '): - sortname = release['ArtistName'][4:] - else: - sortname = release['ArtistName'] - - if sortname.isdigit(): - firstchar = '0-9' - else: - firstchar = sortname[0] + try: + year = release['ReleaseDate'][:4] + except TypeError: + year = '' + + artist = release['ArtistName'].replace('/', '_') + album = release['AlbumTitle'].replace('/', '_') + releasetype = release['Type'].replace('/', '_') + + if release['ArtistName'].startswith('The '): + sortname = release['ArtistName'][4:] + else: + sortname = release['ArtistName'] + + if sortname.isdigit(): + firstchar = '0-9' + else: + firstchar = sortname[0] - - albumvalues = { '$Artist': artist, - '$Album': album, - '$Year': year, - '$Type': releasetype, - '$First': firstchar, - '$artist': artist.lower(), - '$album': album.lower(), - '$year': year, - '$type': releasetype.lower(), - '$first': firstchar.lower() - } - - - folder = helpers.replace_all(headphones.FOLDER_FORMAT, albumvalues) - folder = folder.replace('./', '_/').replace(':','_').replace('?','_') - - if folder.endswith('.'): - folder = folder.replace(folder[len(folder)-1], '_') + + albumvalues = { '$Artist': artist, + '$Album': album, + '$Year': year, + '$Type': releasetype, + '$First': firstchar, + '$artist': artist.lower(), + '$album': album.lower(), + '$year': year, + '$type': releasetype.lower(), + '$first': firstchar.lower() + } + + + folder = helpers.replace_all(headphones.FOLDER_FORMAT, albumvalues) + folder = folder.replace('./', '_/').replace(':','_').replace('?','_') + + if folder.endswith('.'): + folder = folder.replace(folder[len(folder)-1], '_') - if not track['TrackNumber']: - tracknumber = '' - else: - tracknumber = '%02d' % track['TrackNumber'] - - title = track['TrackTitle'] - - trackvalues = { '$Track': tracknumber, - '$Title': title, - '$Artist': release['ArtistName'], - '$Album': release['AlbumTitle'], - '$Year': year, - '$track': tracknumber, - '$title': title.lower(), - '$artist': release['ArtistName'].lower(), - '$album': release['AlbumTitle'].lower(), - '$year': year - } - - new_file_name = helpers.replace_all(headphones.FILE_FORMAT, trackvalues).replace('/','_') + '.*' - - new_file_name = new_file_name.replace('?','_').replace(':', '_') - - full_path_to_file = os.path.normpath(os.path.join(headphones.MUSIC_DIR, folder, new_file_name)).encode(headphones.SYS_ENCODING, 'replace') + if not track['TrackNumber']: + tracknumber = '' + else: + tracknumber = '%02d' % track['TrackNumber'] + + title = track['TrackTitle'] + + trackvalues = { '$Track': tracknumber, + '$Title': title, + '$Artist': release['ArtistName'], + '$Album': release['AlbumTitle'], + '$Year': year, + '$track': tracknumber, + '$title': title.lower(), + '$artist': release['ArtistName'].lower(), + '$album': release['AlbumTitle'].lower(), + '$year': year + } + + new_file_name = helpers.replace_all(headphones.FILE_FORMAT, trackvalues).replace('/','_') + '.*' + + new_file_name = new_file_name.replace('?','_').replace(':', '_') + + full_path_to_file = os.path.normpath(os.path.join(headphones.MUSIC_DIR, folder, new_file_name)).encode(headphones.SYS_ENCODING, 'replace') - match = glob.glob(full_path_to_file) - - if match: + match = glob.glob(full_path_to_file) + + if match: - logger.info('Found a match: %s. Writing MBID to metadata' % match[0]) - - unipath = unicode(match[0], headphones.SYS_ENCODING, errors='replace') + logger.info('Found a match: %s. Writing MBID to metadata' % match[0]) + + unipath = unicode(match[0], headphones.SYS_ENCODING, errors='replace') - myDB.action('UPDATE tracks SET Location=? WHERE TrackID=?', [unipath, track['TrackID']]) - myDB.action('DELETE from have WHERE Location=?', [unipath]) - - # Try to insert the appropriate track id so we don't have to keep doing this - try: - f = MediaFile(match[0]) - f.mb_trackid = track['TrackID'] - f.save() - myDB.action('UPDATE tracks SET BitRate=?, Format=? WHERE TrackID=?', [f.bitrate, f.format, track['TrackID']]) + myDB.action('UPDATE tracks SET Location=? WHERE TrackID=?', [unipath, track['TrackID']]) + myDB.action('DELETE from have WHERE Location=?', [unipath]) + + # Try to insert the appropriate track id so we don't have to keep doing this + try: + f = MediaFile(match[0]) + f.mb_trackid = track['TrackID'] + f.save() + myDB.action('UPDATE tracks SET BitRate=?, Format=? WHERE TrackID=?', [f.bitrate, f.format, track['TrackID']]) - logger.debug('Wrote mbid to track: %s' % match[0]) + logger.debug('Wrote mbid to track: %s' % match[0]) - except: - logger.error('Error embedding track id into: %s' % match[0]) - continue + except: + logger.error('Error embedding track id into: %s' % match[0]) + continue - logger.info('Done checking empty filepaths') - logger.info('Done syncing library with directory: %s' % dir) - - # Clean up the new artist list - unique_artists = {}.fromkeys(new_artists).keys() - current_artists = myDB.select('SELECT ArtistName, ArtistID from artists') - - artist_list = [f for f in unique_artists if f.lower() not in [x[0].lower() for x in current_artists]] - - # Update track counts - logger.info('Updating track counts') + logger.info('Done checking empty filepaths') + logger.info('Done syncing library with directory: %s' % dir) + + # Clean up the new artist list + unique_artists = {}.fromkeys(new_artists).keys() + current_artists = myDB.select('SELECT ArtistName, ArtistID from artists') + + artist_list = [f for f in unique_artists if f.lower() not in [x[0].lower() for x in current_artists]] + + # Update track counts + logger.info('Updating track counts') - for artist in current_artists: - havetracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID like ? AND Location IS NOT NULL', [artist['ArtistID']])) + len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ?', [artist['ArtistName']])) - myDB.action('UPDATE artists SET HaveTracks=? WHERE ArtistID=?', [havetracks, artist['ArtistID']]) - - logger.info('Found %i new artists' % len(artist_list)) + for artist in current_artists: + havetracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID like ? AND Location IS NOT NULL', [artist['ArtistID']])) + len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ?', [artist['ArtistName']])) + myDB.action('UPDATE artists SET HaveTracks=? WHERE ArtistID=?', [havetracks, artist['ArtistID']]) + + logger.info('Found %i new artists' % len(artist_list)) - if len(artist_list): - if headphones.ADD_ARTISTS: - logger.info('Importing %i new artists' % len(artist_list)) - importer.artistlist_to_mbids(artist_list) - else: - logger.info('To add these artists, go to Manage->Manage New Artists') - headphones.NEW_ARTISTS = artist_list - - if headphones.DETECT_BITRATE: - headphones.PREFERRED_BITRATE = sum(bitrates)/len(bitrates)/1000 + if len(artist_list): + if headphones.ADD_ARTISTS: + logger.info('Importing %i new artists' % len(artist_list)) + importer.artistlist_to_mbids(artist_list) + else: + logger.info('To add these artists, go to Manage->Manage New Artists') + headphones.NEW_ARTISTS = artist_list + + if headphones.DETECT_BITRATE: + headphones.PREFERRED_BITRATE = sum(bitrates)/len(bitrates)/1000 diff --git a/headphones/logger.py b/headphones/logger.py index 97c435bc..758d1233 100644 --- a/headphones/logger.py +++ b/headphones/logger.py @@ -13,69 +13,69 @@ MAX_FILES = 5 # Simple rotating log handler that uses RotatingFileHandler class RotatingLogger(object): - def __init__(self, filename, max_size, max_files): - - self.filename = filename - self.max_size = max_size - self.max_files = max_files - - - def initLogger(self, verbose=1): - - l = logging.getLogger('headphones') - l.setLevel(logging.DEBUG) - - self.filename = os.path.join(headphones.LOG_DIR, self.filename) - - filehandler = handlers.RotatingFileHandler(self.filename, maxBytes=self.max_size, backupCount=self.max_files) - filehandler.setLevel(logging.DEBUG) - - fileformatter = logging.Formatter('%(asctime)s - %(levelname)-7s :: %(message)s', '%d-%b-%Y %H:%M:%S') - - filehandler.setFormatter(fileformatter) - l.addHandler(filehandler) - - if verbose: - consolehandler = logging.StreamHandler() - if verbose == 1: - consolehandler.setLevel(logging.INFO) - if verbose == 2: - consolehandler.setLevel(logging.DEBUG) - consoleformatter = logging.Formatter('%(asctime)s - %(levelname)s :: %(message)s', '%d-%b-%Y %H:%M:%S') - consolehandler.setFormatter(consoleformatter) - l.addHandler(consolehandler) - - def log(self, message, level): + def __init__(self, filename, max_size, max_files): + + self.filename = filename + self.max_size = max_size + self.max_files = max_files + + + def initLogger(self, verbose=1): + + l = logging.getLogger('headphones') + l.setLevel(logging.DEBUG) + + self.filename = os.path.join(headphones.LOG_DIR, self.filename) + + filehandler = handlers.RotatingFileHandler(self.filename, maxBytes=self.max_size, backupCount=self.max_files) + filehandler.setLevel(logging.DEBUG) + + fileformatter = logging.Formatter('%(asctime)s - %(levelname)-7s :: %(message)s', '%d-%b-%Y %H:%M:%S') + + filehandler.setFormatter(fileformatter) + l.addHandler(filehandler) + + if verbose: + consolehandler = logging.StreamHandler() + if verbose == 1: + consolehandler.setLevel(logging.INFO) + if verbose == 2: + consolehandler.setLevel(logging.DEBUG) + consoleformatter = logging.Formatter('%(asctime)s - %(levelname)s :: %(message)s', '%d-%b-%Y %H:%M:%S') + consolehandler.setFormatter(consoleformatter) + l.addHandler(consolehandler) + + def log(self, message, level): - logger = logging.getLogger('headphones') - - threadname = threading.currentThread().getName() - - if level != 'DEBUG': - headphones.LOG_LIST.insert(0, (helpers.now(), message, level, threadname)) - - message = threadname + ' : ' + message + logger = logging.getLogger('headphones') + + threadname = threading.currentThread().getName() + + if level != 'DEBUG': + headphones.LOG_LIST.insert(0, (helpers.now(), message, level, threadname)) + + message = threadname + ' : ' + message - if level == 'DEBUG': - logger.debug(message) - elif level == 'INFO': - logger.info(message) - elif level == 'WARNING': - logger.warn(message) - else: - logger.error(message) + if level == 'DEBUG': + logger.debug(message) + elif level == 'INFO': + logger.info(message) + elif level == 'WARNING': + logger.warn(message) + else: + logger.error(message) headphones_log = RotatingLogger('headphones.log', MAX_SIZE, MAX_FILES) def debug(message): - headphones_log.log(message, level='DEBUG') + headphones_log.log(message, level='DEBUG') def info(message): - headphones_log.log(message, level='INFO') - + headphones_log.log(message, level='INFO') + def warn(message): - headphones_log.log(message, level='WARNING') - + headphones_log.log(message, level='WARNING') + def error(message): - headphones_log.log(message, level='ERROR') - + headphones_log.log(message, level='ERROR') + diff --git a/headphones/lyrics.py b/headphones/lyrics.py index 3c95676e..6ce42b57 100644 --- a/headphones/lyrics.py +++ b/headphones/lyrics.py @@ -7,53 +7,53 @@ from headphones import logger def getLyrics(artist, song): - params = { "artist": artist.encode('utf-8'), - "song": song.encode('utf-8'), - "fmt": 'xml' + params = { "artist": artist.encode('utf-8'), + "song": song.encode('utf-8'), + "fmt": 'xml' } - searchURL = 'http://lyrics.wikia.com/api.php?' + urllib.urlencode(params) - - try: - data = urllib.urlopen(searchURL).read() - except Exception, e: - logger.warn('Error opening: %s. Error: %s' % (searchURL, e)) - return - - try: - parseddata = minidom.parseString(data) - except Exception, e: - logger.warn('Error parsing data from url: %s. Error: %s' % (searchURL, e)) - return - - url = parseddata.getElementsByTagName("url") - - if url: - lyricsurl = url[0].firstChild.nodeValue - else: - logger.info('No lyrics found for %s - %s' % (artist, song)) - return - - try: - lyricspage = urllib.urlopen(lyricsurl).read() - except Exception, e: - logger.warn('Error fetching lyrics from: %s. Error: %s' % (lyricsurl, e)) - return - - m = re.compile('''
.*?
(.*?) %s' % (downloaded_track, new_file_name)) - try: - os.rename(downloaded_track, new_file) - except Exception, e: - logger.error('Error renaming file: %s. Error: %s' % (downloaded_track, e)) - continue - + logger.debug('Renaming %s ---> %s' % (downloaded_track, new_file_name)) + try: + os.rename(downloaded_track, new_file) + except Exception, e: + logger.error('Error renaming file: %s. Error: %s' % (downloaded_track, e)) + continue + def updateHave(albumpath): - results = [] - - for r,d,f in os.walk(albumpath): - for files in f: - if any(files.lower().endswith('.' + x.lower()) for x in headphones.MEDIA_FORMATS): - results.append(os.path.join(r, files)) - - if results: - - myDB = db.DBConnection() - - for song in results: - try: - f = MediaFile(song) - #logger.debug('Reading: %s' % song.decode('UTF-8')) - except: - logger.warn('Could not read file: %s' % song) - continue - else: - if f.albumartist: - artist = f.albumartist - elif f.artist: - artist = f.artist - else: - continue - - myDB.action('UPDATE tracks SET Location=?, BitRate=?, Format=? WHERE ArtistName LIKE ? AND AlbumTitle LIKE ? AND TrackTitle LIKE ?', [unicode(song, headphones.SYS_ENCODING, errors="replace"), f.bitrate, f.format, artist, f.album, f.title]) - + results = [] + + for r,d,f in os.walk(albumpath): + for files in f: + if any(files.lower().endswith('.' + x.lower()) for x in headphones.MEDIA_FORMATS): + results.append(os.path.join(r, files)) + + if results: + + myDB = db.DBConnection() + + for song in results: + try: + f = MediaFile(song) + #logger.debug('Reading: %s' % song.decode('UTF-8')) + except: + logger.warn('Could not read file: %s' % song) + continue + else: + if f.albumartist: + artist = f.albumartist + elif f.artist: + artist = f.artist + else: + continue + + myDB.action('UPDATE tracks SET Location=?, BitRate=?, Format=? WHERE ArtistName LIKE ? AND AlbumTitle LIKE ? AND TrackTitle LIKE ?', [unicode(song, headphones.SYS_ENCODING, errors="replace"), f.bitrate, f.format, artist, f.album, f.title]) + def renameUnprocessedFolder(albumpath): - - i = 0 - while True: - if i == 0: - new_folder_name = albumpath + ' (Unprocessed)' - else: - new_folder_name = albumpath + ' (Unprocessed)[%i]' % i - - if os.path.exists(new_folder_name): - i += 1 - - else: - os.rename(albumpath, new_folder_name) - return - + + i = 0 + while True: + if i == 0: + new_folder_name = albumpath + ' (Unprocessed)' + else: + new_folder_name = albumpath + ' (Unprocessed)[%i]' % i + + if os.path.exists(new_folder_name): + i += 1 + + else: + os.rename(albumpath, new_folder_name) + return + def forcePostProcess(): - - if not headphones.DOWNLOAD_DIR: - logger.error('No DOWNLOAD_DIR has been set. Set "Music Download Directory:" to your SAB download directory on the settings page.') - return - else: - processing = "nzb" - processing_next = "torrent" - while processing != "done": - if headphones.DOWNLOAD_DIR and processing == "nzb": - download_dir = headphones.DOWNLOAD_DIR.encode('utf-8') - if not headphones.DOWNLOAD_TORRENT_DIR: - processing_next = "done" - if headphones.DOWNLOAD_TORRENT_DIR and processing == "torrent": - download_dir = headphones.DOWNLOAD_TORRENT_DIR.encode('utf-8') - processing_next = "done" - if not headphones.DOWNLOAD_DIR and processing == "nzb": - download_dir = headphones.DOWNLOAD_TORRENT_DIR.encode('utf-8') - processing_next = "done" - - logger.info('Checking to see if there are any folders to process in download_dir: %s' % download_dir) - # Get a list of folders in the download_dir - folders = [d for d in os.listdir(download_dir) if os.path.isdir(os.path.join(download_dir, d))] - - if len(folders): - logger.info('Found %i folders to process' % len(folders)) - pass - else: - logger.info('Found no folders to process in: %s' % download_dir) - return - - # Parse the folder names to get artist album info - for folder in folders: - - albumpath = os.path.join(download_dir, folder) - folder = unicode(folder, headphones.SYS_ENCODING, errors='replace') - - logger.info('Processing: %s' % folder) - - try: - name, album, year = helpers.extract_data(folder) - except: - logger.info("Couldn't parse " + folder + " into any valid format.") - continue - if name and album and year: - - myDB = db.DBConnection() - release = myDB.action('SELECT AlbumID, ArtistName, AlbumTitle from albums WHERE ArtistName LIKE ? and AlbumTitle LIKE ?', [name, album]).fetchone() - if release: - logger.info('Found a match in the database: %s - %s. Verifying to make sure it is the correct album' % (release['ArtistName'], release['AlbumTitle'])) - verify(release['AlbumID'], albumpath) - else: - logger.info('Querying MusicBrainz for the release group id for: %s - %s' % (name, album)) - from headphones import mb - try: - rgid = mb.findAlbumID(helpers.latinToAscii(name), helpers.latinToAscii(album)) - except: - logger.error('Can not get release information for this album') - continue - if rgid: - verify(rgid, albumpath) - else: - logger.info('No match found on MusicBrainz for: %s - %s' % (name, album)) - processing = processing_next + + if not headphones.DOWNLOAD_DIR: + logger.error('No DOWNLOAD_DIR has been set. Set "Music Download Directory:" to your SAB download directory on the settings page.') + return + else: + processing = "nzb" + processing_next = "torrent" + while processing != "done": + if headphones.DOWNLOAD_DIR and processing == "nzb": + download_dir = headphones.DOWNLOAD_DIR.encode('utf-8') + if not headphones.DOWNLOAD_TORRENT_DIR: + processing_next = "done" + if headphones.DOWNLOAD_TORRENT_DIR and processing == "torrent": + download_dir = headphones.DOWNLOAD_TORRENT_DIR.encode('utf-8') + processing_next = "done" + if not headphones.DOWNLOAD_DIR and processing == "nzb": + download_dir = headphones.DOWNLOAD_TORRENT_DIR.encode('utf-8') + processing_next = "done" + + logger.info('Checking to see if there are any folders to process in download_dir: %s' % download_dir) + # Get a list of folders in the download_dir + folders = [d for d in os.listdir(download_dir) if os.path.isdir(os.path.join(download_dir, d))] + + if len(folders): + logger.info('Found %i folders to process' % len(folders)) + pass + else: + logger.info('Found no folders to process in: %s' % download_dir) + return + + # Parse the folder names to get artist album info + for folder in folders: + + albumpath = os.path.join(download_dir, folder) + folder = unicode(folder, headphones.SYS_ENCODING, errors='replace') + + logger.info('Processing: %s' % folder) + + try: + name, album, year = helpers.extract_data(folder) + except: + logger.info("Couldn't parse " + folder + " into any valid format.") + continue + if name and album and year: + + myDB = db.DBConnection() + release = myDB.action('SELECT AlbumID, ArtistName, AlbumTitle from albums WHERE ArtistName LIKE ? and AlbumTitle LIKE ?', [name, album]).fetchone() + if release: + logger.info('Found a match in the database: %s - %s. Verifying to make sure it is the correct album' % (release['ArtistName'], release['AlbumTitle'])) + verify(release['AlbumID'], albumpath) + else: + logger.info('Querying MusicBrainz for the release group id for: %s - %s' % (name, album)) + from headphones import mb + try: + rgid = mb.findAlbumID(helpers.latinToAscii(name), helpers.latinToAscii(album)) + except: + logger.error('Can not get release information for this album') + continue + if rgid: + verify(rgid, albumpath) + else: + logger.info('No match found on MusicBrainz for: %s - %s' % (name, album)) + processing = processing_next diff --git a/headphones/sab.py b/headphones/sab.py index 98085ba2..1f5a5889 100644 --- a/headphones/sab.py +++ b/headphones/sab.py @@ -66,7 +66,7 @@ def sendNZB(nzb): multiPartParams = {"nzbfile": (nzb.name+".nzb", nzb.extraInfo[0])} if not headphones.SAB_HOST.startswith('http'): - headphones.SAB_HOST = 'http://' + headphones.SAB_HOST + headphones.SAB_HOST = 'http://' + headphones.SAB_HOST if headphones.SAB_HOST.endswith('/'): headphones.SAB_HOST = headphones.SAB_HOST[0:len(headphones.SAB_HOST)-1] diff --git a/headphones/searcher.py b/headphones/searcher.py index 0ed33eaf..4f8166c9 100644 --- a/headphones/searcher.py +++ b/headphones/searcher.py @@ -126,9 +126,9 @@ def searchNZB(albumid=None, new=False, losslessOnly=False): if albums[0] in albums[1] or len(albums[0]) < 4 or len(albums[1]) < 4: term = cleanartist + ' ' + cleanalbum + ' ' + year elif albums[0] == 'Various Artists': - term = cleanalbum + ' ' + year + term = cleanalbum + ' ' + year else: - term = cleanartist + ' ' + cleanalbum + term = cleanartist + ' ' + cleanalbum # Replace bad characters in the term and unicode it term = re.sub('[\.\-\/]', ' ', term).encode('utf-8') @@ -152,7 +152,7 @@ def searchNZB(albumid=None, new=False, losslessOnly=False): # hopefully this will fix it for now. If you notice anything else it gets stuck on, please post it # on Github so it can be added if term.lower().startswith("the "): - term = term[4:] + term = term[4:] params = { "page": "download", @@ -169,26 +169,26 @@ def searchNZB(albumid=None, new=False, losslessOnly=False): searchURL = "http://rss.nzbmatrix.com/rss.php?" + urllib.urlencode(params) logger.info(u'Parsing results from NZBMatrix' % searchURL) try: - data = urllib2.urlopen(searchURL, timeout=20).read() + data = urllib2.urlopen(searchURL, timeout=20).read() except urllib2.URLError, e: - logger.warn('Error fetching data from NZBMatrix: %s' % e) - data = False - + logger.warn('Error fetching data from NZBMatrix: %s' % e) + data = False + if data: - d = feedparser.parse(data) - - for item in d.entries: - try: - url = item.link - title = item.title - size = int(item.links[1]['length']) - - resultlist.append((title, size, url, provider)) - logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size))) - - except AttributeError, e: - logger.info(u"No results found from NZBMatrix for %s" % term) + d = feedparser.parse(data) + + for item in d.entries: + try: + url = item.link + title = item.title + size = int(item.links[1]['length']) + + resultlist.append((title, size, url, provider)) + logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size))) + + except AttributeError, e: + logger.info(u"No results found from NZBMatrix for %s" % term) if headphones.NEWZNAB: provider = "newznab" @@ -211,31 +211,31 @@ def searchNZB(albumid=None, new=False, losslessOnly=False): logger.info(u'Parsing results from %s' % (searchURL, headphones.NEWZNAB_HOST)) try: - data = urllib2.urlopen(searchURL, timeout=20).read() + data = urllib2.urlopen(searchURL, timeout=20).read() except urllib2.URLError, e: - logger.warn('Error fetching data from %s: %s' % (headphones.NEWZNAB_HOST, e)) - data = False - + logger.warn('Error fetching data from %s: %s' % (headphones.NEWZNAB_HOST, e)) + data = False + if data: - - d = feedparser.parse(data) - - if not len(d.entries): - logger.info(u"No results found from %s for %s" % (headphones.NEWZNAB_HOST, term)) - pass - - else: - for item in d.entries: - try: - url = item.link - title = item.title - size = int(item.links[1]['length']) - - resultlist.append((title, size, url, provider)) - logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size))) - - except Exception, e: - logger.error(u"An unknown error occured trying to parse the feed: %s" % e) + + d = feedparser.parse(data) + + if not len(d.entries): + logger.info(u"No results found from %s for %s" % (headphones.NEWZNAB_HOST, term)) + pass + + else: + for item in d.entries: + try: + url = item.link + title = item.title + size = int(item.links[1]['length']) + + resultlist.append((title, size, url, provider)) + logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size))) + + except Exception, e: + logger.error(u"An unknown error occured trying to parse the feed: %s" % e) if headphones.NZBSORG: provider = "nzbsorg" @@ -258,31 +258,31 @@ def searchNZB(albumid=None, new=False, losslessOnly=False): logger.info(u'Parsing results from nzbs.org' % searchURL) try: - data = urllib2.urlopen(searchURL, timeout=20).read() + data = urllib2.urlopen(searchURL, timeout=20).read() except urllib2.URLError, e: - logger.warn('Error fetching data from nzbs.org: %s' % e) - data = False - + logger.warn('Error fetching data from nzbs.org: %s' % e) + data = False + if data: - - d = feedparser.parse(data) - - if not len(d.entries): - logger.info(u"No results found from nzbs.org for %s" % term) - pass - - else: - for item in d.entries: - try: - url = item.link - title = item.title - size = int(item.links[1]['length']) - - resultlist.append((title, size, url, provider)) - logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size))) - - except Exception, e: - logger.error(u"An unknown error occured trying to parse the feed: %s" % e) + + d = feedparser.parse(data) + + if not len(d.entries): + logger.info(u"No results found from nzbs.org for %s" % term) + pass + + else: + for item in d.entries: + try: + url = item.link + title = item.title + size = int(item.links[1]['length']) + + resultlist.append((title, size, url, provider)) + logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size))) + + except Exception, e: + logger.error(u"An unknown error occured trying to parse the feed: %s" % e) if headphones.NEWZBIN: provider = "newzbin" @@ -300,9 +300,9 @@ def searchNZB(albumid=None, new=False, losslessOnly=False): params = { "fpn": "p", 'u_nfo_posts_only': 0, - 'u_url_posts_only': 0, - 'u_comment_posts_only': 0, - 'u_show_passworded': 0, + 'u_url_posts_only': 0, + 'u_comment_posts_only': 0, + 'u_show_passworded': 0, "searchaction": "Search", #"dl": 1, "category": categories, @@ -403,28 +403,28 @@ def searchNZB(albumid=None, new=False, losslessOnly=False): if new: - while True: - - if len(nzblist): - - alreadydownloaded = myDB.select('SELECT * from snatched WHERE URL=?', [nzblist[0][2]]) - - if len(alreadydownloaded): - logger.info('%s has already been downloaded. Skipping.' % nzblist[0][0]) - nzblist.pop(0) - - else: - break - else: - logger.info('No more results found for %s' % term) - return "none" + while True: + + if len(nzblist): + + alreadydownloaded = myDB.select('SELECT * from snatched WHERE URL=?', [nzblist[0][2]]) + + if len(alreadydownloaded): + logger.info('%s has already been downloaded. Skipping.' % nzblist[0][0]) + nzblist.pop(0) + + else: + break + else: + logger.info('No more results found for %s' % term) + return "none" logger.info(u"Pre-processing result") (data, bestqual) = preprocess(nzblist) if data and bestqual: - logger.info(u'Found best result: %s - %s' % (bestqual[2], bestqual[0], helpers.bytes_to_mb(bestqual[1]))) + logger.info(u'Found best result: %s - %s' % (bestqual[2], bestqual[0], helpers.bytes_to_mb(bestqual[1]))) nzb_folder_name = '%s - %s [%s]' % (helpers.latinToAscii(albums[0]).encode('UTF-8').replace('/', '_'), helpers.latinToAscii(albums[1]).encode('UTF-8').replace('/', '_'), year) if headphones.SAB_HOST and not headphones.BLACKHOLE: @@ -455,9 +455,9 @@ def searchNZB(albumid=None, new=False, losslessOnly=False): def verifyresult(title, artistterm, term): - - title = re.sub('[\.\-\/\_]', ' ', title) - + + title = re.sub('[\.\-\/\_]', ' ', title) + #if artistterm != 'Various Artists': # # if not re.search('^' + re.escape(artistterm), title, re.IGNORECASE): @@ -472,23 +472,23 @@ def verifyresult(title, artistterm, term): #another attempt to weed out substrings. We don't want "Vol III" when we were looking for "Vol II" - tokens = re.split('\W', term, re.IGNORECASE | re.UNICODE) - for token in tokens: + tokens = re.split('\W', term, re.IGNORECASE | re.UNICODE) + for token in tokens: - if not token: - continue - if token == 'Various' or token == 'Artists' or token == 'VA': - continue - if not re.search('(?:\W|^)+' + token + '(?:\W|$)+', title, re.IGNORECASE | re.UNICODE): - cleantoken = ''.join(c for c in token if c not in string.punctuation) - if not not re.search('(?:\W|^)+' + cleantoken + '(?:\W|$)+', title, re.IGNORECASE | re.UNICODE): - dic = {'!':'i', '$':'s'} - dumbtoken = helpers.replace_all(token, dic) - if not not re.search('(?:\W|^)+' + dumbtoken + '(?:\W|$)+', title, re.IGNORECASE | re.UNICODE): - logger.info("Removed from results: " + title + " (missing tokens: " + token + " and " + cleantoken + ")") - return False - - return True + if not token: + continue + if token == 'Various' or token == 'Artists' or token == 'VA': + continue + if not re.search('(?:\W|^)+' + token + '(?:\W|$)+', title, re.IGNORECASE | re.UNICODE): + cleantoken = ''.join(c for c in token if c not in string.punctuation) + if not not re.search('(?:\W|^)+' + cleantoken + '(?:\W|$)+', title, re.IGNORECASE | re.UNICODE): + dic = {'!':'i', '$':'s'} + dumbtoken = helpers.replace_all(token, dic) + if not not re.search('(?:\W|^)+' + dumbtoken + '(?:\W|$)+', title, re.IGNORECASE | re.UNICODE): + logger.info("Removed from results: " + title + " (missing tokens: " + token + " and " + cleantoken + ")") + return False + + return True def getresultNZB(result): @@ -521,7 +521,7 @@ def preprocess(resultlist): usenet_retention = 2000 else: usenet_retention = int(headphones.USENET_RETENTION) - + for result in resultlist: nzb = getresultNZB(result) if nzb: @@ -581,9 +581,9 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False): if albums[0] in albums[1] or len(albums[0]) < 4 or len(albums[1]) < 4: term = cleanartist + ' ' + cleanalbum + ' ' + year elif albums[0] == 'Various Artists': - term = cleanalbum + ' ' + year + term = cleanalbum + ' ' + year else: - term = cleanartist + ' ' + cleanalbum + term = cleanartist + ' ' + cleanalbum # Replace bad characters in the term and unicode it term = re.sub('[\.\-\/]', ' ', term).encode('utf-8') @@ -619,51 +619,50 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False): searchURL = providerurl + "/?%s" % urllib.urlencode(params) try: - data = urllib2.urlopen(searchURL, timeout=20).read() + data = urllib2.urlopen(searchURL, timeout=20).read() except urllib2.URLError, e: - logger.warn('Error fetching data from %s: %s' % (provider, e)) - data = False + logger.warn('Error fetching data from %s: %s' % (provider, e)) + data = False if data: - - d = feedparser.parse(data) - if not len(d.entries): - logger.info(u"No results found from %s for %s" % (provider, term)) - pass - - else: - for item in d.entries: - try: - rightformat = True - title = item.title - seeders = item.seeds - url = item.links[1]['url'] - size = int(item.links[1]['length']) - try: - if format == "2": - request = urllib2.Request(url) - request.add_header('Accept-encoding', 'gzip') - response = urllib2.urlopen(request) - if response.info().get('Content-Encoding') == 'gzip': - buf = StringIO( response.read()) - f = gzip.GzipFile(fileobj=buf) - torrent = f.read() - else: - torrent = response.read() - if int(torrent.find(".mp3")) > 0 and int(torrent.find(".flac")) < 1: - rightformat = False - except Exception, e: - rightformat = False - if rightformat == True and size < maxsize and minimumseeders < int(seeders): - resultlist.append((title, size, url, provider)) - logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size))) - else: - logger.info('%s is larger than the maxsize, the wrong format or has to little seeders for this category, skipping. (Size: %i bytes, Seeders: %i, Format: %s)' % (title, size, int(seeders), rightformat)) - - except Exception, e: - logger.error(u"An unknown error occured in the KAT parser: %s" % e) + + d = feedparser.parse(data) + if not len(d.entries): + logger.info(u"No results found from %s for %s" % (provider, term)) + pass + + else: + for item in d.entries: + try: + rightformat = True + title = item.title + seeders = item.seeds + url = item.links[1]['url'] + size = int(item.links[1]['length']) + try: + if format == "2": + request = urllib2.Request(url) + request.add_header('Accept-encoding', 'gzip') + response = urllib2.urlopen(request) + if response.info().get('Content-Encoding') == 'gzip': + buf = StringIO( response.read()) + f = gzip.GzipFile(fileobj=buf) + torrent = f.read() + else: + torrent = response.read() + if int(torrent.find(".mp3")) > 0 and int(torrent.find(".flac")) < 1: + rightformat = False + except Exception, e: + rightformat = False + if rightformat == True and size < maxsize and minimumseeders < int(seeders): + resultlist.append((title, size, url, provider)) + logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size))) + else: + logger.info('%s is larger than the maxsize, the wrong format or has to little seeders for this category, skipping. (Size: %i bytes, Seeders: %i, Format: %s)' % (title, size, int(seeders), rightformat)) + + except Exception, e: + logger.error(u"An unknown error occured in the KAT parser: %s" % e) - if headphones.ISOHUNT: provider = "ISOhunt" providerurl = url_fix("http://isohunt.com/js/rss/" + term) @@ -687,54 +686,54 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False): searchURL = providerurl + "?%s" % urllib.urlencode(params) try: - data = urllib2.urlopen(searchURL, timeout=20).read() + data = urllib2.urlopen(searchURL, timeout=20).read() except urllib2.URLError, e: - logger.warn('Error fetching data from %s: %s' % (provider, e)) - data = False + logger.warn('Error fetching data from %s: %s' % (provider, e)) + data = False if data: - - d = feedparser.parse(data) - if not len(d.entries): - logger.info(u"No results found from %s for %s" % (provider, term)) - pass - - else: - for item in d.entries: - try: - rightformat = True - title = re.sub(r"(?<= \[)(.+)(?=\])","",item.title) - title = title.replace("[]","") - sxstart = item.description.find("Seeds: ") + 7 - seeds = "" - while item.description[sxstart:sxstart + 1] != " ": - seeds = seeds + item.description[sxstart:sxstart + 1] - sxstart = sxstart + 1 - url = item.links[1]['url'] - size = int(item.links[1]['length']) - try: - if format == "2": - request = urllib2.Request(url) - request.add_header('Accept-encoding', 'gzip') - response = urllib2.urlopen(request) - if response.info().get('Content-Encoding') == 'gzip': - buf = StringIO( response.read()) - f = gzip.GzipFile(fileobj=buf) - torrent = f.read() - else: - torrent = response.read() - if int(torrent.find(".mp3")) > 0 and int(torrent.find(".flac")) < 1: - rightformat = False - except Exception, e: - rightformat = False - if rightformat == True and size < maxsize and minimumseeders < seeds: - resultlist.append((title, size, url, provider)) - logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size))) - else: - logger.info('%s is larger than the maxsize, the wrong format or has to little seeders for this category, skipping. (Size: %i bytes, Seeders: %i, Format: %s)' % (title, size, int(seeds), rightformat)) - - except Exception, e: - logger.error(u"An unknown error occured in the ISOhunt parser: %s" % e) + + d = feedparser.parse(data) + if not len(d.entries): + logger.info(u"No results found from %s for %s" % (provider, term)) + pass + + else: + for item in d.entries: + try: + rightformat = True + title = re.sub(r"(?<= \[)(.+)(?=\])","",item.title) + title = title.replace("[]","") + sxstart = item.description.find("Seeds: ") + 7 + seeds = "" + while item.description[sxstart:sxstart + 1] != " ": + seeds = seeds + item.description[sxstart:sxstart + 1] + sxstart = sxstart + 1 + url = item.links[1]['url'] + size = int(item.links[1]['length']) + try: + if format == "2": + request = urllib2.Request(url) + request.add_header('Accept-encoding', 'gzip') + response = urllib2.urlopen(request) + if response.info().get('Content-Encoding') == 'gzip': + buf = StringIO( response.read()) + f = gzip.GzipFile(fileobj=buf) + torrent = f.read() + else: + torrent = response.read() + if int(torrent.find(".mp3")) > 0 and int(torrent.find(".flac")) < 1: + rightformat = False + except Exception, e: + rightformat = False + if rightformat == True and size < maxsize and minimumseeders < seeds: + resultlist.append((title, size, url, provider)) + logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size))) + else: + logger.info('%s is larger than the maxsize, the wrong format or has to little seeders for this category, skipping. (Size: %i bytes, Seeders: %i, Format: %s)' % (title, size, int(seeds), rightformat)) + + except Exception, e: + logger.error(u"An unknown error occured in the ISOhunt parser: %s" % e) if headphones.MININOVA: provider = "Mininova" @@ -755,53 +754,53 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False): searchURL = providerurl try: - data = urllib2.urlopen(searchURL, timeout=20).read() + data = urllib2.urlopen(searchURL, timeout=20).read() except urllib2.URLError, e: - logger.warn('Error fetching data from %s: %s' % (provider, e)) - data = False + logger.warn('Error fetching data from %s: %s' % (provider, e)) + data = False if data: - - d = feedparser.parse(data) - if not len(d.entries): - logger.info(u"No results found from %s for %s" % (provider, term)) - pass - - else: - for item in d.entries: - try: - rightformat = True - title = item.title - sxstart = item.description.find("Ratio: ") + 7 - seeds = "" - while item.description[sxstart:sxstart + 1] != " ": - seeds = seeds + item.description[sxstart:sxstart + 1] - sxstart = sxstart + 1 - url = item.links[1]['url'] - size = int(item.links[1]['length']) - try: - if format == "2": - request = urllib2.Request(url) - request.add_header('Accept-encoding', 'gzip') - response = urllib2.urlopen(request) - if response.info().get('Content-Encoding') == 'gzip': - buf = StringIO( response.read()) - f = gzip.GzipFile(fileobj=buf) - torrent = f.read() - else: - torrent = response.read() - if int(torrent.find(".mp3")) > 0 and int(torrent.find(".flac")) < 1: - rightformat = False - except Exception, e: - rightformat = False - if rightformat == True and size < maxsize and minimumseeders < seeds: - resultlist.append((title, size, url, provider)) - logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size))) - else: - logger.info('%s is larger than the maxsize, the wrong format or has to little seeders for this category, skipping. (Size: %i bytes, Seeders: %i, Format: %s)' % (title, size, int(seeds), rightformat)) - - except Exception, e: - logger.error(u"An unknown error occured in the MiniNova Parser: %s" % e) + + d = feedparser.parse(data) + if not len(d.entries): + logger.info(u"No results found from %s for %s" % (provider, term)) + pass + + else: + for item in d.entries: + try: + rightformat = True + title = item.title + sxstart = item.description.find("Ratio: ") + 7 + seeds = "" + while item.description[sxstart:sxstart + 1] != " ": + seeds = seeds + item.description[sxstart:sxstart + 1] + sxstart = sxstart + 1 + url = item.links[1]['url'] + size = int(item.links[1]['length']) + try: + if format == "2": + request = urllib2.Request(url) + request.add_header('Accept-encoding', 'gzip') + response = urllib2.urlopen(request) + if response.info().get('Content-Encoding') == 'gzip': + buf = StringIO( response.read()) + f = gzip.GzipFile(fileobj=buf) + torrent = f.read() + else: + torrent = response.read() + if int(torrent.find(".mp3")) > 0 and int(torrent.find(".flac")) < 1: + rightformat = False + except Exception, e: + rightformat = False + if rightformat == True and size < maxsize and minimumseeders < seeds: + resultlist.append((title, size, url, provider)) + logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size))) + else: + logger.info('%s is larger than the maxsize, the wrong format or has to little seeders for this category, skipping. (Size: %i bytes, Seeders: %i, Format: %s)' % (title, size, int(seeds), rightformat)) + + except Exception, e: + logger.error(u"An unknown error occured in the MiniNova Parser: %s" % e) @@ -847,28 +846,28 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False): if new: - while True: - - if len(torrentlist): - - alreadydownloaded = myDB.select('SELECT * from snatched WHERE URL=?', [torrentlist[0][2]]) - - if len(alreadydownloaded): - logger.info('%s has already been downloaded. Skipping.' % torrentlist[0][0]) - torrentlist.pop(0) - - else: - break - else: - logger.info('No more results found for %s' % term) - return + while True: + + if len(torrentlist): + + alreadydownloaded = myDB.select('SELECT * from snatched WHERE URL=?', [torrentlist[0][2]]) + + if len(alreadydownloaded): + logger.info('%s has already been downloaded. Skipping.' % torrentlist[0][0]) + torrentlist.pop(0) + + else: + break + else: + logger.info('No more results found for %s' % term) + return logger.info(u"Pre-processing result") (data, bestqual) = preprocesstorrent(torrentlist) if data and bestqual: - logger.info(u'Found best result: %s - %s' % (bestqual[2], bestqual[0], helpers.bytes_to_mb(bestqual[1]))) + logger.info(u'Found best result: %s - %s' % (bestqual[2], bestqual[0], helpers.bytes_to_mb(bestqual[1]))) torrent_folder_name = '%s - %s [%s]' % (helpers.latinToAscii(albums[0]).encode('UTF-8').replace('/', '_'), helpers.latinToAscii(albums[1]).encode('UTF-8').replace('/', '_'), year) if headphones.TORRENTBLACKHOLE_DIR == "sendtracker": diff --git a/headphones/templates.py b/headphones/templates.py deleted file mode 100644 index 5e922bd7..00000000 --- a/headphones/templates.py +++ /dev/null @@ -1,440 +0,0 @@ -from headphones import db - -_header = ''' - - - Headphones - - - - - -
''' - -_shutdownheader = ''' - - - Headphones - - - - - - -
''' - -_logobar = ''' - -
- ''' - -_nav = '''''' - -_footer = ''' -
- - ''' - -configform = form = ''' -
-
- -
-
-
-
-

Web Interface

- - - - - - - - - - - - - - - - -
-

- HTTP Host:

-
- i.e. localhost or 0.0.0.0 -

-
-

- HTTP Username:

- -

-
-

- HTTP Port:

- -

-
-

- HTTP Password:

- -

-
-

Launch Browser on Startup:

-
- -

Download Settings

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

SABnzbd Host:


- - usually localhost:8080 -
-

SABnzbd Username:

-
-
- -

SABnzbd API:

-
-
- -

SABnzbd Password:

-
-
- -

SABnzbd Category:

-
-
- -

Music Download Directory:


- - Full path to the directory where SAB downloads your music
- i.e. /Users/name/Downloads/music
-
-
- -

Use Black Hole:

-
-
- -

Black Hole Directory:


- - Folder your Download program watches for NZBs -
-
- -

Usenet Retention:

-
- -

Search Providers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

NZBMatrix:

-
-

- NZBMatrix Username:
- -

-
-

- NZBMatrix API:
- -

-
-
- -

Newznab:

-
-
- -

- Newznab Host:
-
- i.e. http://nzb.su -

-
-
- -

- Newznab API:
- -

-
-
- -

NZBs.org:

-
-
- -

- NZBs.org UID:
- -

-
-
- -

- NZBs.org Hash:
- -

-
-
- -

Newzbin:

-
-
- -

- Newzbin UID:
- -

-
-
- -

- Newzbin Password:
- -

-
- -

Quality & Post Processing

- - - - - - - - - - -
- Album Quality: -

- Highest Quality excluding Lossless

- Highest Quality including Lossless

- Lossless Only

- Preferred Bitrate: - kbps
- Auto-Detect Preferred Bitrate -

-
- Post-Processing: -

- Move downloads to Destination Folder
- Rename files
- Correct metadata
- Delete leftover files (.m3u, .nfo, .sfv, .nzb, etc.)
- Add album art as 'folder.jpg' to album folder
- Embed album art in each file -

-
-
- -

Path to Destination folder:
-
- i.e. /Users/name/Music/iTunes or /Volumes/share/music -

-
- -

Advanced Settings

- - - - - - - - - -
- Renaming Options: -
- -

Folder Format:
-
- Use: artist, album, year and first (first letter in artist name)
- E.g.: first/artist/album [year] = G/Girl Talk/All Day [2010]
-

- -

File Format:
-
- Use: tracknumber, title, artist, album and year -

-
- Miscellaneous: -

- Automatically Include Extras When Adding an Artist
- Extras includes: EPs, Compilations, Live Albums, Remix Albums and Singles -

-

Log Directory:
-

-
- Prowl Notification: -

- Enabled? -

-

- API key: - -

-

- Notify on snatch?

-

Priority (-2,-1,0,1 or 2): -

-
- -


- (Web Interface changes require a restart to take effect)

-
-
-
''' - - -def displayAlbums(ArtistID, Type=None): - - myDB = db.DBConnection() - - results = myDB.select('SELECT AlbumTitle, ReleaseDate, AlbumID, Status, ArtistName, AlbumASIN from albums WHERE ArtistID=? AND Type=? order by ReleaseDate DESC', [ArtistID, Type]) - - if not len(results): - return - - typeheadings = {'Album' : 'Official Albums', - 'Compilation': 'Compilations', - 'EP': 'EPs', - 'Live': 'Live Albums', - 'Remix': 'Remixes', - 'Single': 'Singles'} - - page = ['''

%s

- - - - - - - - ''' % typeheadings[Type]] - i = 0 - while i < len(results): - totaltracks = len(myDB.select('SELECT TrackTitle from tracks WHERE AlbumID=?', [results[i][2]])) - havetracks = len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ? AND AlbumTitle like ?', [results[i][4], results[i][0]])) - try: - percent = (havetracks*100)/totaltracks - if percent > 100: - percent = 100 - except ZeroDivisionError: - percent = 100 - if results[i][3] == 'Skipped': - newStatus = '''%s [want]''' % (results[i][3], results[i][2], ArtistID) - elif results[i][3] == 'Wanted': - newStatus = '''%s[skip]''' % (results[i][3], results[i][2], ArtistID) - elif results[i][3] == 'Downloaded': - newStatus = '''%s[retry][new]''' % (results[i][3], results[i][2], ArtistID, results[i][2], ArtistID) - elif results[i][3] == 'Snatched': - newStatus = '''%s[retry][new]''' % (results[i][3], results[i][2], ArtistID, results[i][2], ArtistID) - else: - newStatus = '%s' % (results[i][3]) - page.append(''' - - - - - ''' % (results[i][5], results[i][2], results[i][0], results[i][2], results[i][1], newStatus, percent, havetracks, totaltracks)) - i = i+1 - page.append('
Album NameRelease DateStatusHave
- %s - (link)%s%s
%s/%s

') - - return ''.join(page) diff --git a/headphones/updater.py b/headphones/updater.py index 1ea2974b..3aa5e847 100644 --- a/headphones/updater.py +++ b/headphones/updater.py @@ -4,15 +4,15 @@ from headphones import logger, db, importer def dbUpdate(): - myDB = db.DBConnection() + myDB = db.DBConnection() - activeartists = myDB.select('SELECT ArtistID, ArtistName from artists WHERE Status="Active" or Status="Loading" order by LastUpdated ASC') + activeartists = myDB.select('SELECT ArtistID, ArtistName from artists WHERE Status="Active" or Status="Loading" order by LastUpdated ASC') - logger.info('Starting update for %i active artists' % len(activeartists)) - - for artist in activeartists: - - artistid = artist[0] - importer.addArtisttoDB(artistid) - - logger.info('Update complete') + logger.info('Starting update for %i active artists' % len(activeartists)) + + for artist in activeartists: + + artistid = artist[0] + importer.addArtisttoDB(artistid) + + logger.info('Update complete') diff --git a/headphones/versioncheck.py b/headphones/versioncheck.py index 88c9a81f..669b2e5e 100644 --- a/headphones/versioncheck.py +++ b/headphones/versioncheck.py @@ -10,205 +10,205 @@ branch = "master" def runGit(args): - if headphones.GIT_PATH: - git_locations = ['"'+headphones.GIT_PATH+'"'] - else: - git_locations = ['git'] - - if platform.system().lower() == 'darwin': - git_locations.append('/usr/local/git/bin/git') - - - output = err = None - - for cur_git in git_locations: - - cmd = cur_git+' '+args - - try: - logger.debug('Trying to execute: "' + cmd + '" with shell in ' + headphones.PROG_DIR) - p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, cwd=headphones.PROG_DIR) - output, err = p.communicate() - logger.debug('Git output: ' + output) - except OSError: - logger.debug('Command ' + cmd + ' didn\'t work, couldn\'t find git') - continue - - if 'not found' in output or "not recognized as an internal or external command" in output: - logger.debug('Unable to find git with command ' + cmd) - output = None - elif 'fatal:' in output or err: - logger.error('Git returned bad info. Are you sure this is a git installation?') - output = None - elif output: - break - - return (output, err) - + if headphones.GIT_PATH: + git_locations = ['"'+headphones.GIT_PATH+'"'] + else: + git_locations = ['git'] + + if platform.system().lower() == 'darwin': + git_locations.append('/usr/local/git/bin/git') + + + output = err = None + + for cur_git in git_locations: + + cmd = cur_git+' '+args + + try: + logger.debug('Trying to execute: "' + cmd + '" with shell in ' + headphones.PROG_DIR) + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, cwd=headphones.PROG_DIR) + output, err = p.communicate() + logger.debug('Git output: ' + output) + except OSError: + logger.debug('Command ' + cmd + ' didn\'t work, couldn\'t find git') + continue + + if 'not found' in output or "not recognized as an internal or external command" in output: + logger.debug('Unable to find git with command ' + cmd) + output = None + elif 'fatal:' in output or err: + logger.error('Git returned bad info. Are you sure this is a git installation?') + output = None + elif output: + break + + return (output, err) + def getVersion(): - if version.HEADPHONES_VERSION.startswith('build '): - - headphones.INSTALL_TYPE = 'win' - - # Don't have a way to update exe yet, but don't want to set VERSION to None - return 'Windows Install' - - elif os.path.isdir(os.path.join(headphones.PROG_DIR, '.git')): - - headphones.INSTALL_TYPE = 'git' - output, err = runGit('rev-parse HEAD') - - if not output: - logger.error('Couldn\'t find latest installed version.') - return None - - cur_commit_hash = output.strip() - - if not re.match('^[a-z0-9]+$', cur_commit_hash): - logger.error('Output doesn\'t look like a hash, not using it') - return None - - return cur_commit_hash - - else: - - headphones.INSTALL_TYPE = 'source' - - version_file = os.path.join(headphones.PROG_DIR, 'version.txt') - - if not os.path.isfile(version_file): - return None - - fp = open(version_file, 'r') - current_version = fp.read().strip(' \n\r') - fp.close() - - if current_version: - return current_version - else: - return None - + if version.HEADPHONES_VERSION.startswith('build '): + + headphones.INSTALL_TYPE = 'win' + + # Don't have a way to update exe yet, but don't want to set VERSION to None + return 'Windows Install' + + elif os.path.isdir(os.path.join(headphones.PROG_DIR, '.git')): + + headphones.INSTALL_TYPE = 'git' + output, err = runGit('rev-parse HEAD') + + if not output: + logger.error('Couldn\'t find latest installed version.') + return None + + cur_commit_hash = output.strip() + + if not re.match('^[a-z0-9]+$', cur_commit_hash): + logger.error('Output doesn\'t look like a hash, not using it') + return None + + return cur_commit_hash + + else: + + headphones.INSTALL_TYPE = 'source' + + version_file = os.path.join(headphones.PROG_DIR, 'version.txt') + + if not os.path.isfile(version_file): + return None + + fp = open(version_file, 'r') + current_version = fp.read().strip(' \n\r') + fp.close() + + if current_version: + return current_version + else: + return None + def checkGithub(): - # Get the latest commit available from github - url = 'https://api.github.com/repos/%s/headphones/commits/%s' % (user, branch) - logger.info ('Retrieving latest version information from github') - try: - result = urllib2.urlopen(url).read() - git = simplejson.JSONDecoder().decode(result) - headphones.LATEST_VERSION = git['sha'] - except: - logger.warn('Could not get the latest commit from github') - headphones.COMMITS_BEHIND = 0 - return headphones.CURRENT_VERSION - - # See how many commits behind we are - if headphones.CURRENT_VERSION: - logger.info('Comparing currently installed version with latest github version') - url = 'https://api.github.com/repos/%s/headphones/compare/%s...%s' % (user, headphones.CURRENT_VERSION, headphones.LATEST_VERSION) - - try: - result = urllib2.urlopen(url).read() - git = simplejson.JSONDecoder().decode(result) - headphones.COMMITS_BEHIND = git['total_commits'] - except: - logger.warn('Could not get commits behind from github') - headphones.COMMITS_BEHIND = 0 - return headphones.CURRENT_VERSION - - if headphones.COMMITS_BEHIND >= 1: - logger.info('New version is available. You are %s commits behind' % headphones.COMMITS_BEHIND) - elif headphones.COMMITS_BEHIND == 0: - logger.info('Headphones is up to date') - elif headphones.COMMITS_BEHIND == -1: - logger.info('You are running an unknown version of Headphones. Run the updater to identify your version') - - else: - logger.info('You are running an unknown version of Headphones. Run the updater to identify your version') - - return headphones.LATEST_VERSION - + # Get the latest commit available from github + url = 'https://api.github.com/repos/%s/headphones/commits/%s' % (user, branch) + logger.info ('Retrieving latest version information from github') + try: + result = urllib2.urlopen(url).read() + git = simplejson.JSONDecoder().decode(result) + headphones.LATEST_VERSION = git['sha'] + except: + logger.warn('Could not get the latest commit from github') + headphones.COMMITS_BEHIND = 0 + return headphones.CURRENT_VERSION + + # See how many commits behind we are + if headphones.CURRENT_VERSION: + logger.info('Comparing currently installed version with latest github version') + url = 'https://api.github.com/repos/%s/headphones/compare/%s...%s' % (user, headphones.CURRENT_VERSION, headphones.LATEST_VERSION) + + try: + result = urllib2.urlopen(url).read() + git = simplejson.JSONDecoder().decode(result) + headphones.COMMITS_BEHIND = git['total_commits'] + except: + logger.warn('Could not get commits behind from github') + headphones.COMMITS_BEHIND = 0 + return headphones.CURRENT_VERSION + + if headphones.COMMITS_BEHIND >= 1: + logger.info('New version is available. You are %s commits behind' % headphones.COMMITS_BEHIND) + elif headphones.COMMITS_BEHIND == 0: + logger.info('Headphones is up to date') + elif headphones.COMMITS_BEHIND == -1: + logger.info('You are running an unknown version of Headphones. Run the updater to identify your version') + + else: + logger.info('You are running an unknown version of Headphones. Run the updater to identify your version') + + return headphones.LATEST_VERSION + def update(): - - if headphones.INSTALL_TYPE == 'win': - - logger.info('Windows .exe updating not supported yet.') - pass - + + if headphones.INSTALL_TYPE == 'win': + + logger.info('Windows .exe updating not supported yet.') + pass + - elif headphones.INSTALL_TYPE == 'git': - - output, err = runGit('pull origin ' + version.HEADPHONES_VERSION) - - if not output: - logger.error('Couldn\'t download latest version') - - for line in output.split('\n'): - - if 'Already up-to-date.' in line: - logger.info('No update available, not updating') - logger.info('Output: ' + str(output)) - elif line.endswith('Aborting.'): - logger.error('Unable to update from git: '+line) - logger.info('Output: ' + str(output)) - - else: - - tar_download_url = 'https://github.com/%s/headphones/tarball/%s' % (user, branch) - update_dir = os.path.join(headphones.PROG_DIR, 'update') - version_path = os.path.join(headphones.PROG_DIR, 'version.txt') - - try: - logger.info('Downloading update from: '+tar_download_url) - data = urllib2.urlopen(tar_download_url) - except (IOError, URLError): - logger.error("Unable to retrieve new version from "+tar_download_url+", can't update") - return - - download_name = data.geturl().split('/')[-1] - - tar_download_path = os.path.join(headphones.PROG_DIR, download_name) - - # Save tar to disk - f = open(tar_download_path, 'wb') - f.write(data.read()) - f.close() - - # Extract the tar to update folder - logger.info('Extracing file' + tar_download_path) - tar = tarfile.open(tar_download_path) - tar.extractall(update_dir) - tar.close() - - # Delete the tar.gz - logger.info('Deleting file' + tar_download_path) - os.remove(tar_download_path) - - # Find update dir name - update_dir_contents = [x for x in os.listdir(update_dir) if os.path.isdir(os.path.join(update_dir, x))] - if len(update_dir_contents) != 1: - logger.error(u"Invalid update data, update failed: "+str(update_dir_contents)) - return - content_dir = os.path.join(update_dir, update_dir_contents[0]) - - # walk temp folder and move files to main folder - for dirname, dirnames, filenames in os.walk(content_dir): - dirname = dirname[len(content_dir)+1:] - for curfile in filenames: - old_path = os.path.join(content_dir, dirname, curfile) - new_path = os.path.join(headphones.PROG_DIR, dirname, curfile) - - if os.path.isfile(new_path): - os.remove(new_path) - os.renames(old_path, new_path) - - # Update version.txt - try: - ver_file = open(version_path, 'w') - ver_file.write(headphones.LATEST_VERSION) - ver_file.close() - except IOError, e: - logger.error(u"Unable to write current version to version.txt, update not complete: "+ex(e)) - return + elif headphones.INSTALL_TYPE == 'git': + + output, err = runGit('pull origin ' + version.HEADPHONES_VERSION) + + if not output: + logger.error('Couldn\'t download latest version') + + for line in output.split('\n'): + + if 'Already up-to-date.' in line: + logger.info('No update available, not updating') + logger.info('Output: ' + str(output)) + elif line.endswith('Aborting.'): + logger.error('Unable to update from git: '+line) + logger.info('Output: ' + str(output)) + + else: + + tar_download_url = 'https://github.com/%s/headphones/tarball/%s' % (user, branch) + update_dir = os.path.join(headphones.PROG_DIR, 'update') + version_path = os.path.join(headphones.PROG_DIR, 'version.txt') + + try: + logger.info('Downloading update from: '+tar_download_url) + data = urllib2.urlopen(tar_download_url) + except (IOError, URLError): + logger.error("Unable to retrieve new version from "+tar_download_url+", can't update") + return + + download_name = data.geturl().split('/')[-1] + + tar_download_path = os.path.join(headphones.PROG_DIR, download_name) + + # Save tar to disk + f = open(tar_download_path, 'wb') + f.write(data.read()) + f.close() + + # Extract the tar to update folder + logger.info('Extracing file' + tar_download_path) + tar = tarfile.open(tar_download_path) + tar.extractall(update_dir) + tar.close() + + # Delete the tar.gz + logger.info('Deleting file' + tar_download_path) + os.remove(tar_download_path) + + # Find update dir name + update_dir_contents = [x for x in os.listdir(update_dir) if os.path.isdir(os.path.join(update_dir, x))] + if len(update_dir_contents) != 1: + logger.error(u"Invalid update data, update failed: "+str(update_dir_contents)) + return + content_dir = os.path.join(update_dir, update_dir_contents[0]) + + # walk temp folder and move files to main folder + for dirname, dirnames, filenames in os.walk(content_dir): + dirname = dirname[len(content_dir)+1:] + for curfile in filenames: + old_path = os.path.join(content_dir, dirname, curfile) + new_path = os.path.join(headphones.PROG_DIR, dirname, curfile) + + if os.path.isfile(new_path): + os.remove(new_path) + os.renames(old_path, new_path) + + # Update version.txt + try: + ver_file = open(version_path, 'w') + ver_file.write(headphones.LATEST_VERSION) + ver_file.close() + except IOError, e: + logger.error(u"Unable to write current version to version.txt, update not complete: "+ex(e)) + return diff --git a/headphones/webserve.py b/headphones/webserve.py index 055d0964..13b9c5fa 100644 --- a/headphones/webserve.py +++ b/headphones/webserve.py @@ -17,562 +17,562 @@ from headphones.helpers import checked, radio def serve_template(templatename, **kwargs): - interface_dir = os.path.join(str(headphones.PROG_DIR), 'data/interfaces/') - template_dir = os.path.join(str(interface_dir), headphones.INTERFACE) - - _hplookup = TemplateLookup(directories=[template_dir]) - - try: - template = _hplookup.get_template(templatename) - return template.render(**kwargs) - except: - return exceptions.html_error_template().render() - + interface_dir = os.path.join(str(headphones.PROG_DIR), 'data/interfaces/') + template_dir = os.path.join(str(interface_dir), headphones.INTERFACE) + + _hplookup = TemplateLookup(directories=[template_dir]) + + try: + template = _hplookup.get_template(templatename) + return template.render(**kwargs) + except: + return exceptions.html_error_template().render() + class WebInterface(object): - - def index(self): - raise cherrypy.HTTPRedirect("home") - index.exposed=True + + def index(self): + raise cherrypy.HTTPRedirect("home") + index.exposed=True - def home(self): - myDB = db.DBConnection() - artists = myDB.select('SELECT * from artists order by ArtistSortName COLLATE NOCASE') - return serve_template(templatename="index.html", title="Home", artists=artists) - home.exposed = True + def home(self): + myDB = db.DBConnection() + artists = myDB.select('SELECT * from artists order by ArtistSortName COLLATE NOCASE') + return serve_template(templatename="index.html", title="Home", artists=artists) + home.exposed = True - def artistPage(self, ArtistID): - myDB = db.DBConnection() - artist = myDB.action('SELECT * FROM artists WHERE ArtistID=?', [ArtistID]).fetchone() - albums = myDB.select('SELECT * from albums WHERE ArtistID=? order by ReleaseDate DESC', [ArtistID]) - if artist is None: - raise cherrypy.HTTPRedirect("home") - return serve_template(templatename="artist.html", title=artist['ArtistName'], artist=artist, albums=albums) - artistPage.exposed = True - - - def albumPage(self, AlbumID): - myDB = db.DBConnection() - album = myDB.action('SELECT * from albums WHERE AlbumID=?', [AlbumID]).fetchone() - tracks = myDB.select('SELECT * from tracks WHERE AlbumID=?', [AlbumID]) - description = myDB.action('SELECT * from descriptions WHERE ReleaseGroupID=?', [AlbumID]).fetchone() - title = album['ArtistName'] + ' - ' + album['AlbumTitle'] - return serve_template(templatename="album.html", title=title, album=album, tracks=tracks, description=description) - albumPage.exposed = True - - - def search(self, name, type): - if len(name) == 0: - raise cherrypy.HTTPRedirect("home") - if type == 'artist': - searchresults = mb.findArtist(name, limit=100) - else: - searchresults = mb.findRelease(name, limit=100) - return serve_template(templatename="searchresults.html", title='Search Results for: "' + name + '"', searchresults=searchresults, type=type) - search.exposed = True + def artistPage(self, ArtistID): + myDB = db.DBConnection() + artist = myDB.action('SELECT * FROM artists WHERE ArtistID=?', [ArtistID]).fetchone() + albums = myDB.select('SELECT * from albums WHERE ArtistID=? order by ReleaseDate DESC', [ArtistID]) + if artist is None: + raise cherrypy.HTTPRedirect("home") + return serve_template(templatename="artist.html", title=artist['ArtistName'], artist=artist, albums=albums) + artistPage.exposed = True + + + def albumPage(self, AlbumID): + myDB = db.DBConnection() + album = myDB.action('SELECT * from albums WHERE AlbumID=?', [AlbumID]).fetchone() + tracks = myDB.select('SELECT * from tracks WHERE AlbumID=?', [AlbumID]) + description = myDB.action('SELECT * from descriptions WHERE ReleaseGroupID=?', [AlbumID]).fetchone() + title = album['ArtistName'] + ' - ' + album['AlbumTitle'] + return serve_template(templatename="album.html", title=title, album=album, tracks=tracks, description=description) + albumPage.exposed = True + + + def search(self, name, type): + if len(name) == 0: + raise cherrypy.HTTPRedirect("home") + if type == 'artist': + searchresults = mb.findArtist(name, limit=100) + else: + searchresults = mb.findRelease(name, limit=100) + return serve_template(templatename="searchresults.html", title='Search Results for: "' + name + '"', searchresults=searchresults, type=type) + search.exposed = True - def addArtist(self, artistid): - threading.Thread(target=importer.addArtisttoDB, args=[artistid]).start() - threading.Thread(target=lastfm.getSimilar).start() - raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % artistid) - addArtist.exposed = True - - def getExtras(self, ArtistID): - myDB = db.DBConnection() - controlValueDict = {'ArtistID': ArtistID} - newValueDict = {'IncludeExtras': 1} - myDB.upsert("artists", newValueDict, controlValueDict) - threading.Thread(target=importer.addArtisttoDB, args=[ArtistID, True]).start() - raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) - getExtras.exposed = True - - def removeExtras(self, ArtistID): - myDB = db.DBConnection() - controlValueDict = {'ArtistID': ArtistID} - newValueDict = {'IncludeExtras': 0} - myDB.upsert("artists", newValueDict, controlValueDict) - extraalbums = myDB.select('SELECT AlbumID from albums WHERE ArtistID=? AND Status="Skipped" AND Type!="Album"', [ArtistID]) - for album in extraalbums: - myDB.action('DELETE from tracks WHERE ArtistID=? AND AlbumID=?', [ArtistID, album['AlbumID']]) - myDB.action('DELETE from albums WHERE ArtistID=? AND AlbumID=?', [ArtistID, album['AlbumID']]) - raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) - removeExtras.exposed = True - - def pauseArtist(self, ArtistID): - logger.info(u"Pausing artist: " + ArtistID) - myDB = db.DBConnection() - controlValueDict = {'ArtistID': ArtistID} - newValueDict = {'Status': 'Paused'} - myDB.upsert("artists", newValueDict, controlValueDict) - raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) - pauseArtist.exposed = True - - def resumeArtist(self, ArtistID): - logger.info(u"Resuming artist: " + ArtistID) - myDB = db.DBConnection() - controlValueDict = {'ArtistID': ArtistID} - newValueDict = {'Status': 'Active'} - myDB.upsert("artists", newValueDict, controlValueDict) - raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) - resumeArtist.exposed = True - - def deleteArtist(self, ArtistID): - logger.info(u"Deleting all traces of artist: " + ArtistID) - myDB = db.DBConnection() - myDB.action('DELETE from artists WHERE ArtistID=?', [ArtistID]) - myDB.action('DELETE from albums WHERE ArtistID=?', [ArtistID]) - myDB.action('DELETE from tracks WHERE ArtistID=?', [ArtistID]) - raise cherrypy.HTTPRedirect("home") - deleteArtist.exposed = True - - def refreshArtist(self, ArtistID): - importer.addArtisttoDB(ArtistID) - raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) - refreshArtist.exposed=True - - def markAlbums(self, ArtistID=None, action=None, **args): - myDB = db.DBConnection() - if action == 'WantedNew': - newaction = 'Wanted' - else: - newaction = action - for mbid in args: - controlValueDict = {'AlbumID': mbid} - newValueDict = {'Status': newaction} - myDB.upsert("albums", newValueDict, controlValueDict) - if action == 'Wanted': - searcher.searchforalbum(mbid, new=False) - if action == 'WantedNew': - searcher.searchforalbum(mbid, new=True) - if ArtistID: - raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) - else: - raise cherrypy.HTTPRedirect("upcoming") - markAlbums.exposed = True - - def addArtists(self, **args): - threading.Thread(target=importer.artistlist_to_mbids, args=[args, True]).start() - raise cherrypy.HTTPRedirect("home") - addArtists.exposed = True - - def queueAlbum(self, AlbumID, ArtistID=None, new=False, redirect=None, lossless=False): - logger.info(u"Marking album: " + AlbumID + " as wanted...") - myDB = db.DBConnection() - controlValueDict = {'AlbumID': AlbumID} - if lossless: - newValueDict = {'Status': 'Wanted Lossless'} - logger.info("...lossless only!") - else: - newValueDict = {'Status': 'Wanted'} - myDB.upsert("albums", newValueDict, controlValueDict) - searcher.searchforalbum(AlbumID, new) - if ArtistID: - raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) - else: - raise cherrypy.HTTPRedirect(redirect) - queueAlbum.exposed = True + def addArtist(self, artistid): + threading.Thread(target=importer.addArtisttoDB, args=[artistid]).start() + threading.Thread(target=lastfm.getSimilar).start() + raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % artistid) + addArtist.exposed = True + + def getExtras(self, ArtistID): + myDB = db.DBConnection() + controlValueDict = {'ArtistID': ArtistID} + newValueDict = {'IncludeExtras': 1} + myDB.upsert("artists", newValueDict, controlValueDict) + threading.Thread(target=importer.addArtisttoDB, args=[ArtistID, True]).start() + raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) + getExtras.exposed = True + + def removeExtras(self, ArtistID): + myDB = db.DBConnection() + controlValueDict = {'ArtistID': ArtistID} + newValueDict = {'IncludeExtras': 0} + myDB.upsert("artists", newValueDict, controlValueDict) + extraalbums = myDB.select('SELECT AlbumID from albums WHERE ArtistID=? AND Status="Skipped" AND Type!="Album"', [ArtistID]) + for album in extraalbums: + myDB.action('DELETE from tracks WHERE ArtistID=? AND AlbumID=?', [ArtistID, album['AlbumID']]) + myDB.action('DELETE from albums WHERE ArtistID=? AND AlbumID=?', [ArtistID, album['AlbumID']]) + raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) + removeExtras.exposed = True + + def pauseArtist(self, ArtistID): + logger.info(u"Pausing artist: " + ArtistID) + myDB = db.DBConnection() + controlValueDict = {'ArtistID': ArtistID} + newValueDict = {'Status': 'Paused'} + myDB.upsert("artists", newValueDict, controlValueDict) + raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) + pauseArtist.exposed = True + + def resumeArtist(self, ArtistID): + logger.info(u"Resuming artist: " + ArtistID) + myDB = db.DBConnection() + controlValueDict = {'ArtistID': ArtistID} + newValueDict = {'Status': 'Active'} + myDB.upsert("artists", newValueDict, controlValueDict) + raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) + resumeArtist.exposed = True + + def deleteArtist(self, ArtistID): + logger.info(u"Deleting all traces of artist: " + ArtistID) + myDB = db.DBConnection() + myDB.action('DELETE from artists WHERE ArtistID=?', [ArtistID]) + myDB.action('DELETE from albums WHERE ArtistID=?', [ArtistID]) + myDB.action('DELETE from tracks WHERE ArtistID=?', [ArtistID]) + raise cherrypy.HTTPRedirect("home") + deleteArtist.exposed = True + + def refreshArtist(self, ArtistID): + importer.addArtisttoDB(ArtistID) + raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) + refreshArtist.exposed=True + + def markAlbums(self, ArtistID=None, action=None, **args): + myDB = db.DBConnection() + if action == 'WantedNew': + newaction = 'Wanted' + else: + newaction = action + for mbid in args: + controlValueDict = {'AlbumID': mbid} + newValueDict = {'Status': newaction} + myDB.upsert("albums", newValueDict, controlValueDict) + if action == 'Wanted': + searcher.searchforalbum(mbid, new=False) + if action == 'WantedNew': + searcher.searchforalbum(mbid, new=True) + if ArtistID: + raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) + else: + raise cherrypy.HTTPRedirect("upcoming") + markAlbums.exposed = True + + def addArtists(self, **args): + threading.Thread(target=importer.artistlist_to_mbids, args=[args, True]).start() + raise cherrypy.HTTPRedirect("home") + addArtists.exposed = True + + def queueAlbum(self, AlbumID, ArtistID=None, new=False, redirect=None, lossless=False): + logger.info(u"Marking album: " + AlbumID + " as wanted...") + myDB = db.DBConnection() + controlValueDict = {'AlbumID': AlbumID} + if lossless: + newValueDict = {'Status': 'Wanted Lossless'} + logger.info("...lossless only!") + else: + newValueDict = {'Status': 'Wanted'} + myDB.upsert("albums", newValueDict, controlValueDict) + searcher.searchforalbum(AlbumID, new) + if ArtistID: + raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) + else: + raise cherrypy.HTTPRedirect(redirect) + queueAlbum.exposed = True - def unqueueAlbum(self, AlbumID, ArtistID): - logger.info(u"Marking album: " + AlbumID + "as skipped...") - myDB = db.DBConnection() - controlValueDict = {'AlbumID': AlbumID} - newValueDict = {'Status': 'Skipped'} - myDB.upsert("albums", newValueDict, controlValueDict) - raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) - unqueueAlbum.exposed = True - - def deleteAlbum(self, AlbumID, ArtistID=None): - logger.info(u"Deleting all traces of album: " + AlbumID) - myDB = db.DBConnection() - myDB.action('DELETE from albums WHERE AlbumID=?', [AlbumID]) - myDB.action('DELETE from tracks WHERE AlbumID=?', [AlbumID]) - if ArtistID: - raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) - else: - raise cherrypy.HTTPRedirect("home") - deleteAlbum.exposed = True + def unqueueAlbum(self, AlbumID, ArtistID): + logger.info(u"Marking album: " + AlbumID + "as skipped...") + myDB = db.DBConnection() + controlValueDict = {'AlbumID': AlbumID} + newValueDict = {'Status': 'Skipped'} + myDB.upsert("albums", newValueDict, controlValueDict) + raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) + unqueueAlbum.exposed = True + + def deleteAlbum(self, AlbumID, ArtistID=None): + logger.info(u"Deleting all traces of album: " + AlbumID) + myDB = db.DBConnection() + myDB.action('DELETE from albums WHERE AlbumID=?', [AlbumID]) + myDB.action('DELETE from tracks WHERE AlbumID=?', [AlbumID]) + if ArtistID: + raise cherrypy.HTTPRedirect("artistPage?ArtistID=%s" % ArtistID) + else: + raise cherrypy.HTTPRedirect("home") + deleteAlbum.exposed = True - def upcoming(self): - myDB = db.DBConnection() - upcoming = myDB.select("SELECT * from albums WHERE ReleaseDate > date('now') order by ReleaseDate DESC") - wanted = myDB.select("SELECT * from albums WHERE Status='Wanted'") - return serve_template(templatename="upcoming.html", title="Upcoming", upcoming=upcoming, wanted=wanted) - upcoming.exposed = True - - def manage(self): - return serve_template(templatename="manage.html", title="Manage") - manage.exposed = True - - def manageArtists(self): - myDB = db.DBConnection() - artists = myDB.select('SELECT * from artists order by ArtistSortName COLLATE NOCASE') - return serve_template(templatename="manageartists.html", title="Manage Artists", artists=artists) - manageArtists.exposed = True - - def manageNew(self): - return serve_template(templatename="managenew.html", title="Manage New Artists") - manageNew.exposed = True - - def markArtists(self, action=None, **args): - myDB = db.DBConnection() - artistsToAdd = [] - for ArtistID in args: - if action == 'delete': - myDB.action('DELETE from artists WHERE ArtistID=?', [ArtistID]) - myDB.action('DELETE from albums WHERE ArtistID=?', [ArtistID]) - myDB.action('DELETE from tracks WHERE ArtistID=?', [ArtistID]) - elif action == 'pause': - controlValueDict = {'ArtistID': ArtistID} - newValueDict = {'Status': 'Paused'} - myDB.upsert("artists", newValueDict, controlValueDict) - elif action == 'resume': - controlValueDict = {'ArtistID': ArtistID} - newValueDict = {'Status': 'Active'} - myDB.upsert("artists", newValueDict, controlValueDict) - else: - artistsToAdd.append(ArtistID) - if len(artistsToAdd) > 0: - logger.debug("Refreshing artists: %s" % artistsToAdd) - threading.Thread(target=importer.addArtistIDListToDB, args=[artistsToAdd]).start() - raise cherrypy.HTTPRedirect("home") - markArtists.exposed = True - - def importLastFM(self, username): - headphones.LASTFM_USERNAME = username - headphones.config_write() - threading.Thread(target=lastfm.getArtists).start() - time.sleep(10) - raise cherrypy.HTTPRedirect("home") - importLastFM.exposed = True - - def importItunes(self, path): - headphones.PATH_TO_XML = path - headphones.config_write() - threading.Thread(target=importer.itunesImport, args=[path]).start() - time.sleep(10) - raise cherrypy.HTTPRedirect("home") - importItunes.exposed = True - - def musicScan(self, path, redirect=None, autoadd=0): - headphones.ADD_ARTISTS = autoadd - headphones.MUSIC_DIR = path - headphones.config_write() - try: - threading.Thread(target=librarysync.libraryScan).start() - except Exception, e: - logger.error('Unable to complete the scan: %s' % e) - time.sleep(10) - if redirect: - raise cherrypy.HTTPRedirect(redirect) - else: - raise cherrypy.HTTPRedirect("home") - musicScan.exposed = True - - def forceUpdate(self): - from headphones import updater - threading.Thread(target=updater.dbUpdate).start() - raise cherrypy.HTTPRedirect("home") - forceUpdate.exposed = True - - def forceSearch(self): - from headphones import searcher - threading.Thread(target=searcher.searchforalbum).start() - raise cherrypy.HTTPRedirect("home") - forceSearch.exposed = True - - def forcePostProcess(self): - from headphones import postprocessor - threading.Thread(target=postprocessor.forcePostProcess).start() - raise cherrypy.HTTPRedirect("home") - forcePostProcess.exposed = True - - def checkGithub(self): - from headphones import versioncheck - versioncheck.checkGithub() - raise cherrypy.HTTPRedirect("home") - checkGithub.exposed = True - - def history(self): - myDB = db.DBConnection() - history = myDB.select('''SELECT * from snatched order by DateAdded DESC''') - return serve_template(templatename="history.html", title="History", history=history) - return page - history.exposed = True - - def logs(self): - return serve_template(templatename="logs.html", title="Log", lineList=headphones.LOG_LIST) - logs.exposed = True - - def clearhistory(self, type=None): - myDB = db.DBConnection() - if type == 'all': - logger.info(u"Clearing all history") - myDB.action('DELETE from snatched') - else: - logger.info(u"Clearing history where status is %s" % type) - myDB.action('DELETE from snatched WHERE Status=?', [type]) - raise cherrypy.HTTPRedirect("history") - clearhistory.exposed = True - - def generateAPI(self): + def upcoming(self): + myDB = db.DBConnection() + upcoming = myDB.select("SELECT * from albums WHERE ReleaseDate > date('now') order by ReleaseDate DESC") + wanted = myDB.select("SELECT * from albums WHERE Status='Wanted'") + return serve_template(templatename="upcoming.html", title="Upcoming", upcoming=upcoming, wanted=wanted) + upcoming.exposed = True + + def manage(self): + return serve_template(templatename="manage.html", title="Manage") + manage.exposed = True + + def manageArtists(self): + myDB = db.DBConnection() + artists = myDB.select('SELECT * from artists order by ArtistSortName COLLATE NOCASE') + return serve_template(templatename="manageartists.html", title="Manage Artists", artists=artists) + manageArtists.exposed = True + + def manageNew(self): + return serve_template(templatename="managenew.html", title="Manage New Artists") + manageNew.exposed = True + + def markArtists(self, action=None, **args): + myDB = db.DBConnection() + artistsToAdd = [] + for ArtistID in args: + if action == 'delete': + myDB.action('DELETE from artists WHERE ArtistID=?', [ArtistID]) + myDB.action('DELETE from albums WHERE ArtistID=?', [ArtistID]) + myDB.action('DELETE from tracks WHERE ArtistID=?', [ArtistID]) + elif action == 'pause': + controlValueDict = {'ArtistID': ArtistID} + newValueDict = {'Status': 'Paused'} + myDB.upsert("artists", newValueDict, controlValueDict) + elif action == 'resume': + controlValueDict = {'ArtistID': ArtistID} + newValueDict = {'Status': 'Active'} + myDB.upsert("artists", newValueDict, controlValueDict) + else: + artistsToAdd.append(ArtistID) + if len(artistsToAdd) > 0: + logger.debug("Refreshing artists: %s" % artistsToAdd) + threading.Thread(target=importer.addArtistIDListToDB, args=[artistsToAdd]).start() + raise cherrypy.HTTPRedirect("home") + markArtists.exposed = True + + def importLastFM(self, username): + headphones.LASTFM_USERNAME = username + headphones.config_write() + threading.Thread(target=lastfm.getArtists).start() + time.sleep(10) + raise cherrypy.HTTPRedirect("home") + importLastFM.exposed = True + + def importItunes(self, path): + headphones.PATH_TO_XML = path + headphones.config_write() + threading.Thread(target=importer.itunesImport, args=[path]).start() + time.sleep(10) + raise cherrypy.HTTPRedirect("home") + importItunes.exposed = True + + def musicScan(self, path, redirect=None, autoadd=0): + headphones.ADD_ARTISTS = autoadd + headphones.MUSIC_DIR = path + headphones.config_write() + try: + threading.Thread(target=librarysync.libraryScan).start() + except Exception, e: + logger.error('Unable to complete the scan: %s' % e) + time.sleep(10) + if redirect: + raise cherrypy.HTTPRedirect(redirect) + else: + raise cherrypy.HTTPRedirect("home") + musicScan.exposed = True + + def forceUpdate(self): + from headphones import updater + threading.Thread(target=updater.dbUpdate).start() + raise cherrypy.HTTPRedirect("home") + forceUpdate.exposed = True + + def forceSearch(self): + from headphones import searcher + threading.Thread(target=searcher.searchforalbum).start() + raise cherrypy.HTTPRedirect("home") + forceSearch.exposed = True + + def forcePostProcess(self): + from headphones import postprocessor + threading.Thread(target=postprocessor.forcePostProcess).start() + raise cherrypy.HTTPRedirect("home") + forcePostProcess.exposed = True + + def checkGithub(self): + from headphones import versioncheck + versioncheck.checkGithub() + raise cherrypy.HTTPRedirect("home") + checkGithub.exposed = True + + def history(self): + myDB = db.DBConnection() + history = myDB.select('''SELECT * from snatched order by DateAdded DESC''') + return serve_template(templatename="history.html", title="History", history=history) + return page + history.exposed = True + + def logs(self): + return serve_template(templatename="logs.html", title="Log", lineList=headphones.LOG_LIST) + logs.exposed = True + + def clearhistory(self, type=None): + myDB = db.DBConnection() + if type == 'all': + logger.info(u"Clearing all history") + myDB.action('DELETE from snatched') + else: + logger.info(u"Clearing history where status is %s" % type) + myDB.action('DELETE from snatched WHERE Status=?', [type]) + raise cherrypy.HTTPRedirect("history") + clearhistory.exposed = True + + def generateAPI(self): - import hashlib, random - - apikey = hashlib.sha224( str(random.getrandbits(256)) ).hexdigest()[0:32] - logger.info("New API generated") - return apikey - - generateAPI.exposed = True - - def config(self): - - interface_dir = os.path.join(headphones.PROG_DIR, 'data/interfaces/') - interface_list = [ name for name in os.listdir(interface_dir) if os.path.isdir(os.path.join(interface_dir, name)) ] + import hashlib, random + + apikey = hashlib.sha224( str(random.getrandbits(256)) ).hexdigest()[0:32] + logger.info("New API generated") + return apikey + + generateAPI.exposed = True + + def config(self): + + interface_dir = os.path.join(headphones.PROG_DIR, 'data/interfaces/') + interface_list = [ name for name in os.listdir(interface_dir) if os.path.isdir(os.path.join(interface_dir, name)) ] - config = { - "http_host" : headphones.HTTP_HOST, - "http_user" : headphones.HTTP_USERNAME, - "http_port" : headphones.HTTP_PORT, - "http_pass" : headphones.HTTP_PASSWORD, - "launch_browser" : checked(headphones.LAUNCH_BROWSER), - "api_enabled" : checked(headphones.API_ENABLED), - "api_key" : headphones.API_KEY, - "download_scan_interval" : headphones.DOWNLOAD_SCAN_INTERVAL, - "nzb_search_interval" : headphones.SEARCH_INTERVAL, - "libraryscan_interval" : headphones.LIBRARYSCAN_INTERVAL, - "sab_host" : headphones.SAB_HOST, - "sab_user" : headphones.SAB_USERNAME, - "sab_api" : headphones.SAB_APIKEY, - "sab_pass" : headphones.SAB_PASSWORD, - "sab_cat" : headphones.SAB_CATEGORY, - "download_dir" : headphones.DOWNLOAD_DIR, - "use_blackhole" : checked(headphones.BLACKHOLE), - "blackhole_dir" : headphones.BLACKHOLE_DIR, - "usenet_retention" : headphones.USENET_RETENTION, - "use_nzbmatrix" : checked(headphones.NZBMATRIX), - "nzbmatrix_user" : headphones.NZBMATRIX_USERNAME, - "nzbmatrix_api" : headphones.NZBMATRIX_APIKEY, - "use_newznab" : checked(headphones.NEWZNAB), - "newznab_host" : headphones.NEWZNAB_HOST, - "newznab_api" : headphones.NEWZNAB_APIKEY, - "use_nzbsorg" : checked(headphones.NZBSORG), - "nzbsorg_uid" : headphones.NZBSORG_UID, - "nzbsorg_hash" : headphones.NZBSORG_HASH, - "use_newzbin" : checked(headphones.NEWZBIN), - "newzbin_uid" : headphones.NEWZBIN_UID, - "newzbin_pass" : headphones.NEWZBIN_PASSWORD, - "torrentblackhole_dir" : headphones.TORRENTBLACKHOLE_DIR, - "download_torrent_dir" : headphones.DOWNLOAD_TORRENT_DIR, - "numberofseeders" : headphones.NUMBEROFSEEDERS, - "use_isohunt" : checked(headphones.ISOHUNT), - "use_kat" : checked(headphones.KAT), - "use_mininova" : checked(headphones.MININOVA), - "pref_qual_0" : radio(headphones.PREFERRED_QUALITY, 0), - "pref_qual_1" : radio(headphones.PREFERRED_QUALITY, 1), - "pref_qual_3" : radio(headphones.PREFERRED_QUALITY, 3), - "pref_qual_2" : radio(headphones.PREFERRED_QUALITY, 2), - "pref_bitrate" : headphones.PREFERRED_BITRATE, - "detect_bitrate" : checked(headphones.DETECT_BITRATE), - "move_files" : checked(headphones.MOVE_FILES), - "rename_files" : checked(headphones.RENAME_FILES), - "correct_metadata" : checked(headphones.CORRECT_METADATA), - "cleanup_files" : checked(headphones.CLEANUP_FILES), - "add_album_art" : checked(headphones.ADD_ALBUM_ART), - "embed_album_art" : checked(headphones.EMBED_ALBUM_ART), - "embed_lyrics" : checked(headphones.EMBED_LYRICS), - "dest_dir" : headphones.DESTINATION_DIR, - "folder_format" : headphones.FOLDER_FORMAT, - "file_format" : headphones.FILE_FORMAT, - "include_extras" : checked(headphones.INCLUDE_EXTRAS), - "autowant_upcoming" : checked(headphones.AUTOWANT_UPCOMING), - "autowant_all" : checked(headphones.AUTOWANT_ALL), - "log_dir" : headphones.LOG_DIR, - "interface_list" : interface_list, - "music_encoder": checked(headphones.MUSIC_ENCODER), - "encoder": headphones.ENCODER, - "bitrate": int(headphones.BITRATE), - "encoderfolder": headphones.ENCODERFOLDER, - "advancedencoder": headphones.ADVANCEDENCODER, - "encoderoutputformat": headphones.ENCODEROUTPUTFORMAT, - "samplingfrequency": headphones.SAMPLINGFREQUENCY, - "encodervbrcbr": headphones.ENCODERVBRCBR, - "encoderquality": headphones.ENCODERQUALITY, - "encoderlossless": checked(headphones.ENCODERLOSSLESS), - "prowl_enabled": checked(headphones.PROWL_ENABLED), - "prowl_onsnatch": checked(headphones.PROWL_ONSNATCH), - "prowl_keys": headphones.PROWL_KEYS, - "prowl_priority": headphones.PROWL_PRIORITY, - "xbmc_enabled": checked(headphones.XBMC_ENABLED), - "xbmc_host": headphones.XBMC_HOST, - "xbmc_username": headphones.XBMC_USERNAME, - "xbmc_password": headphones.XBMC_PASSWORD, - "xbmc_update": checked(headphones.XBMC_UPDATE), - "xbmc_notify": checked(headphones.XBMC_NOTIFY), - "nma_enabled": checked(headphones.NMA_ENABLED), - "nma_apikey": headphones.NMA_APIKEY, - "nma_priority": int(headphones.NMA_PRIORITY), - "mirror_list": headphones.MIRRORLIST, - "mirror": headphones.MIRROR, - "customhost": headphones.CUSTOMHOST, - "customport": headphones.CUSTOMPORT, - "customsleep": headphones.CUSTOMSLEEP, - "hpuser": headphones.HPUSER, - "hppass": headphones.HPPASS - } - return serve_template(templatename="config.html", title="Settings", config=config) - config.exposed = True - - - def configUpdate(self, http_host='0.0.0.0', http_username=None, http_port=8181, http_password=None, launch_browser=0, api_enabled=0, api_key=None, download_scan_interval=None, nzb_search_interval=None, libraryscan_interval=None, - sab_host=None, sab_username=None, sab_apikey=None, sab_password=None, sab_category=None, download_dir=None, blackhole=0, blackhole_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, newzbin=0, newzbin_uid=None, newzbin_password=None, preferred_quality=0, preferred_bitrate=None, detect_bitrate=0, move_files=0, - torrentblackhole_dir=None, download_torrent_dir=None, numberofseeders=10, use_isohunt=0, use_kat=0, use_mininova=0, - rename_files=0, correct_metadata=0, cleanup_files=0, add_album_art=0, embed_album_art=0, embed_lyrics=0, destination_dir=None, folder_format=None, file_format=None, include_extras=0, autowant_upcoming=False, autowant_all=False, interface=None, log_dir=None, - music_encoder=0, encoder=None, bitrate=None, samplingfrequency=None, encoderfolder=None, advancedencoder=None, encoderoutputformat=None, encodervbrcbr=None, encoderquality=None, encoderlossless=0, - prowl_enabled=0, prowl_onsnatch=0, prowl_keys=None, prowl_priority=0, xbmc_enabled=0, xbmc_host=None, xbmc_username=None, xbmc_password=None, xbmc_update=0, xbmc_notify=0, - nma_enabled=False, nma_apikey=None, nma_priority=0, mirror=None, customhost=None, customport=None, customsleep=None, hpuser=None, hppass=None): + config = { + "http_host" : headphones.HTTP_HOST, + "http_user" : headphones.HTTP_USERNAME, + "http_port" : headphones.HTTP_PORT, + "http_pass" : headphones.HTTP_PASSWORD, + "launch_browser" : checked(headphones.LAUNCH_BROWSER), + "api_enabled" : checked(headphones.API_ENABLED), + "api_key" : headphones.API_KEY, + "download_scan_interval" : headphones.DOWNLOAD_SCAN_INTERVAL, + "nzb_search_interval" : headphones.SEARCH_INTERVAL, + "libraryscan_interval" : headphones.LIBRARYSCAN_INTERVAL, + "sab_host" : headphones.SAB_HOST, + "sab_user" : headphones.SAB_USERNAME, + "sab_api" : headphones.SAB_APIKEY, + "sab_pass" : headphones.SAB_PASSWORD, + "sab_cat" : headphones.SAB_CATEGORY, + "download_dir" : headphones.DOWNLOAD_DIR, + "use_blackhole" : checked(headphones.BLACKHOLE), + "blackhole_dir" : headphones.BLACKHOLE_DIR, + "usenet_retention" : headphones.USENET_RETENTION, + "use_nzbmatrix" : checked(headphones.NZBMATRIX), + "nzbmatrix_user" : headphones.NZBMATRIX_USERNAME, + "nzbmatrix_api" : headphones.NZBMATRIX_APIKEY, + "use_newznab" : checked(headphones.NEWZNAB), + "newznab_host" : headphones.NEWZNAB_HOST, + "newznab_api" : headphones.NEWZNAB_APIKEY, + "use_nzbsorg" : checked(headphones.NZBSORG), + "nzbsorg_uid" : headphones.NZBSORG_UID, + "nzbsorg_hash" : headphones.NZBSORG_HASH, + "use_newzbin" : checked(headphones.NEWZBIN), + "newzbin_uid" : headphones.NEWZBIN_UID, + "newzbin_pass" : headphones.NEWZBIN_PASSWORD, + "torrentblackhole_dir" : headphones.TORRENTBLACKHOLE_DIR, + "download_torrent_dir" : headphones.DOWNLOAD_TORRENT_DIR, + "numberofseeders" : headphones.NUMBEROFSEEDERS, + "use_isohunt" : checked(headphones.ISOHUNT), + "use_kat" : checked(headphones.KAT), + "use_mininova" : checked(headphones.MININOVA), + "pref_qual_0" : radio(headphones.PREFERRED_QUALITY, 0), + "pref_qual_1" : radio(headphones.PREFERRED_QUALITY, 1), + "pref_qual_3" : radio(headphones.PREFERRED_QUALITY, 3), + "pref_qual_2" : radio(headphones.PREFERRED_QUALITY, 2), + "pref_bitrate" : headphones.PREFERRED_BITRATE, + "detect_bitrate" : checked(headphones.DETECT_BITRATE), + "move_files" : checked(headphones.MOVE_FILES), + "rename_files" : checked(headphones.RENAME_FILES), + "correct_metadata" : checked(headphones.CORRECT_METADATA), + "cleanup_files" : checked(headphones.CLEANUP_FILES), + "add_album_art" : checked(headphones.ADD_ALBUM_ART), + "embed_album_art" : checked(headphones.EMBED_ALBUM_ART), + "embed_lyrics" : checked(headphones.EMBED_LYRICS), + "dest_dir" : headphones.DESTINATION_DIR, + "folder_format" : headphones.FOLDER_FORMAT, + "file_format" : headphones.FILE_FORMAT, + "include_extras" : checked(headphones.INCLUDE_EXTRAS), + "autowant_upcoming" : checked(headphones.AUTOWANT_UPCOMING), + "autowant_all" : checked(headphones.AUTOWANT_ALL), + "log_dir" : headphones.LOG_DIR, + "interface_list" : interface_list, + "music_encoder": checked(headphones.MUSIC_ENCODER), + "encoder": headphones.ENCODER, + "bitrate": int(headphones.BITRATE), + "encoderfolder": headphones.ENCODERFOLDER, + "advancedencoder": headphones.ADVANCEDENCODER, + "encoderoutputformat": headphones.ENCODEROUTPUTFORMAT, + "samplingfrequency": headphones.SAMPLINGFREQUENCY, + "encodervbrcbr": headphones.ENCODERVBRCBR, + "encoderquality": headphones.ENCODERQUALITY, + "encoderlossless": checked(headphones.ENCODERLOSSLESS), + "prowl_enabled": checked(headphones.PROWL_ENABLED), + "prowl_onsnatch": checked(headphones.PROWL_ONSNATCH), + "prowl_keys": headphones.PROWL_KEYS, + "prowl_priority": headphones.PROWL_PRIORITY, + "xbmc_enabled": checked(headphones.XBMC_ENABLED), + "xbmc_host": headphones.XBMC_HOST, + "xbmc_username": headphones.XBMC_USERNAME, + "xbmc_password": headphones.XBMC_PASSWORD, + "xbmc_update": checked(headphones.XBMC_UPDATE), + "xbmc_notify": checked(headphones.XBMC_NOTIFY), + "nma_enabled": checked(headphones.NMA_ENABLED), + "nma_apikey": headphones.NMA_APIKEY, + "nma_priority": int(headphones.NMA_PRIORITY), + "mirror_list": headphones.MIRRORLIST, + "mirror": headphones.MIRROR, + "customhost": headphones.CUSTOMHOST, + "customport": headphones.CUSTOMPORT, + "customsleep": headphones.CUSTOMSLEEP, + "hpuser": headphones.HPUSER, + "hppass": headphones.HPPASS + } + return serve_template(templatename="config.html", title="Settings", config=config) + config.exposed = True + + + def configUpdate(self, http_host='0.0.0.0', http_username=None, http_port=8181, http_password=None, launch_browser=0, api_enabled=0, api_key=None, download_scan_interval=None, nzb_search_interval=None, libraryscan_interval=None, + sab_host=None, sab_username=None, sab_apikey=None, sab_password=None, sab_category=None, download_dir=None, blackhole=0, blackhole_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, newzbin=0, newzbin_uid=None, newzbin_password=None, preferred_quality=0, preferred_bitrate=None, detect_bitrate=0, move_files=0, + torrentblackhole_dir=None, download_torrent_dir=None, numberofseeders=10, use_isohunt=0, use_kat=0, use_mininova=0, + rename_files=0, correct_metadata=0, cleanup_files=0, add_album_art=0, embed_album_art=0, embed_lyrics=0, destination_dir=None, folder_format=None, file_format=None, include_extras=0, autowant_upcoming=False, autowant_all=False, interface=None, log_dir=None, + music_encoder=0, encoder=None, bitrate=None, samplingfrequency=None, encoderfolder=None, advancedencoder=None, encoderoutputformat=None, encodervbrcbr=None, encoderquality=None, encoderlossless=0, + prowl_enabled=0, prowl_onsnatch=0, prowl_keys=None, prowl_priority=0, xbmc_enabled=0, xbmc_host=None, xbmc_username=None, xbmc_password=None, xbmc_update=0, xbmc_notify=0, + nma_enabled=False, nma_apikey=None, nma_priority=0, mirror=None, customhost=None, customport=None, customsleep=None, hpuser=None, hppass=None): - headphones.HTTP_HOST = http_host - headphones.HTTP_PORT = http_port - headphones.HTTP_USERNAME = http_username - headphones.HTTP_PASSWORD = http_password - headphones.LAUNCH_BROWSER = launch_browser - headphones.API_ENABLED = api_enabled - headphones.API_KEY = api_key - headphones.DOWNLOAD_SCAN_INTERVAL = download_scan_interval - headphones.SEARCH_INTERVAL = nzb_search_interval - headphones.LIBRARYSCAN_INTERVAL = libraryscan_interval - headphones.SAB_HOST = sab_host - headphones.SAB_USERNAME = sab_username - headphones.SAB_PASSWORD = sab_password - headphones.SAB_APIKEY = sab_apikey - headphones.SAB_CATEGORY = sab_category - headphones.DOWNLOAD_DIR = download_dir - headphones.BLACKHOLE = blackhole - headphones.BLACKHOLE_DIR = blackhole_dir - headphones.USENET_RETENTION = usenet_retention - headphones.NZBMATRIX = nzbmatrix - headphones.NZBMATRIX_USERNAME = nzbmatrix_username - headphones.NZBMATRIX_APIKEY = nzbmatrix_apikey - headphones.NEWZNAB = newznab - headphones.NEWZNAB_HOST = newznab_host - headphones.NEWZNAB_APIKEY = newznab_apikey - headphones.NZBSORG = nzbsorg - headphones.NZBSORG_UID = nzbsorg_uid - headphones.NZBSORG_HASH = nzbsorg_hash - headphones.NEWZBIN = newzbin - headphones.NEWZBIN_UID = newzbin_uid - headphones.NEWZBIN_PASSWORD = newzbin_password - headphones.TORRENTBLACKHOLE_DIR = torrentblackhole_dir - headphones.NUMBEROFSEEDERS = numberofseeders - headphones.DOWNLOAD_TORRENT_DIR = download_torrent_dir - headphones.ISOHUNT = use_isohunt - headphones.KAT = use_kat - headphones.MININOVA = use_mininova - headphones.PREFERRED_QUALITY = int(preferred_quality) - headphones.PREFERRED_BITRATE = preferred_bitrate - headphones.DETECT_BITRATE = detect_bitrate - headphones.MOVE_FILES = move_files - headphones.CORRECT_METADATA = correct_metadata - headphones.RENAME_FILES = rename_files - headphones.CLEANUP_FILES = cleanup_files - headphones.ADD_ALBUM_ART = add_album_art - headphones.EMBED_ALBUM_ART = embed_album_art - headphones.EMBED_LYRICS = embed_lyrics - headphones.DESTINATION_DIR = destination_dir - headphones.FOLDER_FORMAT = folder_format - headphones.FILE_FORMAT = file_format - headphones.INCLUDE_EXTRAS = include_extras - headphones.AUTOWANT_UPCOMING = autowant_upcoming - headphones.AUTOWANT_ALL = autowant_all - headphones.INTERFACE = interface - headphones.LOG_DIR = log_dir - headphones.MUSIC_ENCODER = music_encoder - headphones.ENCODER = encoder - headphones.BITRATE = int(bitrate) - headphones.SAMPLINGFREQUENCY = int(samplingfrequency) - headphones.ENCODERFOLDER = encoderfolder - headphones.ADVANCEDENCODER = advancedencoder - headphones.ENCODEROUTPUTFORMAT = encoderoutputformat - headphones.ENCODERVBRCBR = encodervbrcbr - headphones.ENCODERQUALITY = int(encoderquality) - headphones.ENCODERLOSSLESS = encoderlossless - headphones.PROWL_ENABLED = prowl_enabled - headphones.PROWL_ONSNATCH = prowl_onsnatch - headphones.PROWL_KEYS = prowl_keys - headphones.PROWL_PRIORITY = prowl_priority - headphones.XBMC_ENABLED = xbmc_enabled - headphones.XBMC_HOST = xbmc_host - headphones.XBMC_USERNAME = xbmc_username - headphones.XBMC_PASSWORD = xbmc_password - headphones.XBMC_UPDATE = xbmc_update - headphones.XBMC_NOTIFY = xbmc_notify - headphones.NMA_ENABLED = nma_enabled - headphones.NMA_APIKEY = nma_apikey - headphones.NMA_PRIORITY = nma_priority - headphones.MIRROR = mirror - headphones.CUSTOMHOST = customhost - headphones.CUSTOMPORT = customport - headphones.CUSTOMSLEEP = customsleep - headphones.HPUSER = hpuser - headphones.HPPASS = hppass - - headphones.config_write() + headphones.HTTP_HOST = http_host + headphones.HTTP_PORT = http_port + headphones.HTTP_USERNAME = http_username + headphones.HTTP_PASSWORD = http_password + headphones.LAUNCH_BROWSER = launch_browser + headphones.API_ENABLED = api_enabled + headphones.API_KEY = api_key + headphones.DOWNLOAD_SCAN_INTERVAL = download_scan_interval + headphones.SEARCH_INTERVAL = nzb_search_interval + headphones.LIBRARYSCAN_INTERVAL = libraryscan_interval + headphones.SAB_HOST = sab_host + headphones.SAB_USERNAME = sab_username + headphones.SAB_PASSWORD = sab_password + headphones.SAB_APIKEY = sab_apikey + headphones.SAB_CATEGORY = sab_category + headphones.DOWNLOAD_DIR = download_dir + headphones.BLACKHOLE = blackhole + headphones.BLACKHOLE_DIR = blackhole_dir + headphones.USENET_RETENTION = usenet_retention + headphones.NZBMATRIX = nzbmatrix + headphones.NZBMATRIX_USERNAME = nzbmatrix_username + headphones.NZBMATRIX_APIKEY = nzbmatrix_apikey + headphones.NEWZNAB = newznab + headphones.NEWZNAB_HOST = newznab_host + headphones.NEWZNAB_APIKEY = newznab_apikey + headphones.NZBSORG = nzbsorg + headphones.NZBSORG_UID = nzbsorg_uid + headphones.NZBSORG_HASH = nzbsorg_hash + headphones.NEWZBIN = newzbin + headphones.NEWZBIN_UID = newzbin_uid + headphones.NEWZBIN_PASSWORD = newzbin_password + headphones.TORRENTBLACKHOLE_DIR = torrentblackhole_dir + headphones.NUMBEROFSEEDERS = numberofseeders + headphones.DOWNLOAD_TORRENT_DIR = download_torrent_dir + headphones.ISOHUNT = use_isohunt + headphones.KAT = use_kat + headphones.MININOVA = use_mininova + headphones.PREFERRED_QUALITY = int(preferred_quality) + headphones.PREFERRED_BITRATE = preferred_bitrate + headphones.DETECT_BITRATE = detect_bitrate + headphones.MOVE_FILES = move_files + headphones.CORRECT_METADATA = correct_metadata + headphones.RENAME_FILES = rename_files + headphones.CLEANUP_FILES = cleanup_files + headphones.ADD_ALBUM_ART = add_album_art + headphones.EMBED_ALBUM_ART = embed_album_art + headphones.EMBED_LYRICS = embed_lyrics + headphones.DESTINATION_DIR = destination_dir + headphones.FOLDER_FORMAT = folder_format + headphones.FILE_FORMAT = file_format + headphones.INCLUDE_EXTRAS = include_extras + headphones.AUTOWANT_UPCOMING = autowant_upcoming + headphones.AUTOWANT_ALL = autowant_all + headphones.INTERFACE = interface + headphones.LOG_DIR = log_dir + headphones.MUSIC_ENCODER = music_encoder + headphones.ENCODER = encoder + headphones.BITRATE = int(bitrate) + headphones.SAMPLINGFREQUENCY = int(samplingfrequency) + headphones.ENCODERFOLDER = encoderfolder + headphones.ADVANCEDENCODER = advancedencoder + headphones.ENCODEROUTPUTFORMAT = encoderoutputformat + headphones.ENCODERVBRCBR = encodervbrcbr + headphones.ENCODERQUALITY = int(encoderquality) + headphones.ENCODERLOSSLESS = encoderlossless + headphones.PROWL_ENABLED = prowl_enabled + headphones.PROWL_ONSNATCH = prowl_onsnatch + headphones.PROWL_KEYS = prowl_keys + headphones.PROWL_PRIORITY = prowl_priority + headphones.XBMC_ENABLED = xbmc_enabled + headphones.XBMC_HOST = xbmc_host + headphones.XBMC_USERNAME = xbmc_username + headphones.XBMC_PASSWORD = xbmc_password + headphones.XBMC_UPDATE = xbmc_update + headphones.XBMC_NOTIFY = xbmc_notify + headphones.NMA_ENABLED = nma_enabled + headphones.NMA_APIKEY = nma_apikey + headphones.NMA_PRIORITY = nma_priority + headphones.MIRROR = mirror + headphones.CUSTOMHOST = customhost + headphones.CUSTOMPORT = customport + headphones.CUSTOMSLEEP = customsleep + headphones.HPUSER = hpuser + headphones.HPPASS = hppass + + headphones.config_write() - raise cherrypy.HTTPRedirect("config") - - configUpdate.exposed = True + raise cherrypy.HTTPRedirect("config") + + configUpdate.exposed = True - def shutdown(self): - headphones.SIGNAL = 'shutdown' - message = 'Shutting Down...' - return serve_template(templatename="shutdown.html", title="Shutting Down", message=message, timer=15) - return page + def shutdown(self): + headphones.SIGNAL = 'shutdown' + message = 'Shutting Down...' + return serve_template(templatename="shutdown.html", title="Shutting Down", message=message, timer=15) + return page - shutdown.exposed = True + shutdown.exposed = True - def restart(self): - headphones.SIGNAL = 'restart' - message = 'Restarting...' - return serve_template(templatename="shutdown.html", title="Restarting", message=message, timer=30) - restart.exposed = True - - def update(self): - headphones.SIGNAL = 'update' - message = 'Updating...' - return serve_template(templatename="shutdown.html", title="Updating", message=message, timer=120) - return page - update.exposed = True - - def extras(self): - myDB = db.DBConnection() - cloudlist = myDB.select('SELECT * from lastfmcloud') - return serve_template(templatename="extras.html", title="Extras", cloudlist=cloudlist) - return page - extras.exposed = True + def restart(self): + headphones.SIGNAL = 'restart' + message = 'Restarting...' + return serve_template(templatename="shutdown.html", title="Restarting", message=message, timer=30) + restart.exposed = True + + def update(self): + headphones.SIGNAL = 'update' + message = 'Updating...' + return serve_template(templatename="shutdown.html", title="Updating", message=message, timer=120) + return page + update.exposed = True + + def extras(self): + myDB = db.DBConnection() + cloudlist = myDB.select('SELECT * from lastfmcloud') + return serve_template(templatename="extras.html", title="Extras", cloudlist=cloudlist) + return page + extras.exposed = True - def addReleaseById(self, rid): - threading.Thread(target=importer.addReleaseById, args=[rid]).start() - raise cherrypy.HTTPRedirect("home") - addReleaseById.exposed = True - - def updateCloud(self): - - lastfm.getSimilar() - raise cherrypy.HTTPRedirect("extras") - - updateCloud.exposed = True - - def api(self, *args, **kwargs): - - from headphones.api import Api - - a = Api() - - a.checkParams(*args, **kwargs) - - data = a.fetchData() - - return data - - api.exposed = True + def addReleaseById(self, rid): + threading.Thread(target=importer.addReleaseById, args=[rid]).start() + raise cherrypy.HTTPRedirect("home") + addReleaseById.exposed = True + + def updateCloud(self): + + lastfm.getSimilar() + raise cherrypy.HTTPRedirect("extras") + + updateCloud.exposed = True + + def api(self, *args, **kwargs): + + from headphones.api import Api + + a = Api() + + a.checkParams(*args, **kwargs) + + data = a.fetchData() + + return data + + api.exposed = True diff --git a/headphones/webstart.py b/headphones/webstart.py index 2c462c1c..7d0cfa73 100644 --- a/headphones/webstart.py +++ b/headphones/webstart.py @@ -10,16 +10,16 @@ from headphones.webserve import WebInterface def initialize(options={}): - cherrypy.config.update({ - 'log.screen': False, - 'server.thread_pool': 10, - 'server.socket_port': options['http_port'], - 'server.socket_host': options['http_host'], - 'engine.autoreload_on': False, - }) + cherrypy.config.update({ + 'log.screen': False, + 'server.thread_pool': 10, + 'server.socket_port': options['http_port'], + 'server.socket_host': options['http_host'], + 'engine.autoreload_on': False, + }) - conf = { - '/': { + conf = { + '/': { 'tools.staticdir.root': os.path.join(headphones.PROG_DIR, 'data') }, '/interfaces':{ @@ -39,32 +39,32 @@ def initialize(options={}): 'tools.staticdir.dir': "js" }, '/favicon.ico':{ - 'tools.staticfile.on': True, - 'tools.staticfile.filename': "images/favicon.ico" + 'tools.staticfile.on': True, + 'tools.staticfile.filename': "images/favicon.ico" } } - if options['http_password'] != "": - conf['/'].update({ - 'tools.auth_basic.on': True, - 'tools.auth_basic.realm': 'Headphones', - 'tools.auth_basic.checkpassword': cherrypy.lib.auth_basic.checkpassword_dict( - {options['http_username']:options['http_password']}) - }) - + if options['http_password'] != "": + conf['/'].update({ + 'tools.auth_basic.on': True, + 'tools.auth_basic.realm': 'Headphones', + 'tools.auth_basic.checkpassword': cherrypy.lib.auth_basic.checkpassword_dict( + {options['http_username']:options['http_password']}) + }) + - # Prevent time-outs - cherrypy.engine.timeout_monitor.unsubscribe() - - cherrypy.tree.mount(WebInterface(), options['http_root'], config = conf) - - try: - cherrypy.process.servers.check_port(options['http_host'], options['http_port']) - cherrypy.server.start() - except IOError: - print 'Failed to start on port: %i. Is something else running?' % (options['http_port']) - sys.exit(0) - - cherrypy.server.wait() - - \ No newline at end of file + # Prevent time-outs + cherrypy.engine.timeout_monitor.unsubscribe() + + cherrypy.tree.mount(WebInterface(), options['http_root'], config = conf) + + try: + cherrypy.process.servers.check_port(options['http_host'], options['http_port']) + cherrypy.server.start() + except IOError: + print 'Failed to start on port: %i. Is something else running?' % (options['http_port']) + sys.exit(0) + + cherrypy.server.wait() + + From 15cf36a27a08af24777d6843d56e311351d66e20 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 19 Jun 2012 13:01:21 +0530 Subject: [PATCH 03/52] Tabs to whspaces in Headphones.py --- Headphones.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/Headphones.py b/Headphones.py index 65c7d8fc..e7496c66 100644 --- a/Headphones.py +++ b/Headphones.py @@ -120,19 +120,19 @@ def main(): headphones.start() while True: - if not headphones.SIGNAL: - time.sleep(1) - else: - logger.info('Received signal: ' + headphones.SIGNAL) - if headphones.SIGNAL == 'shutdown': - headphones.shutdown() - elif headphones.SIGNAL == 'restart': - headphones.shutdown(restart=True) - else: - headphones.shutdown(restart=True, update=True) - - headphones.SIGNAL = None - + if not headphones.SIGNAL: + time.sleep(1) + else: + logger.info('Received signal: ' + headphones.SIGNAL) + if headphones.SIGNAL == 'shutdown': + headphones.shutdown() + elif headphones.SIGNAL == 'restart': + headphones.shutdown(restart=True) + else: + headphones.shutdown(restart=True, update=True) + + headphones.SIGNAL = None + return if __name__ == "__main__": From 20bd6ae35fb86e602cb3370225e1a124f8eeafb3 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 19 Jun 2012 13:02:12 +0530 Subject: [PATCH 04/52] GPL v3 --- COPYING | 674 ++++++++++++++++++++++++++++++++++++ Headphones.py | 15 + headphones/__init__.py | 15 + headphones/albumart.py | 15 + headphones/api.py | 15 + headphones/classes.py | 29 +- headphones/common.py | 17 +- headphones/db.py | 19 +- headphones/exceptions.py | 15 + headphones/helpers.py | 15 + headphones/importer.py | 15 + headphones/lastfm.py | 15 + headphones/librarysync.py | 15 + headphones/logger.py | 15 + headphones/lyrics.py | 15 + headphones/mb.py | 15 + headphones/music_encoder.py | 15 + headphones/notifiers.py | 15 + headphones/postprocessor.py | 15 + headphones/sab.py | 26 +- headphones/searcher.py | 15 + headphones/updater.py | 15 + headphones/versioncheck.py | 15 + headphones/webserve.py | 15 + headphones/webstart.py | 15 + 25 files changed, 1036 insertions(+), 29 deletions(-) create mode 100644 COPYING diff --git a/COPYING b/COPYING new file mode 100644 index 00000000..94a9ed02 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Headphones.py b/Headphones.py index e7496c66..b6591d75 100644 --- a/Headphones.py +++ b/Headphones.py @@ -1,4 +1,19 @@ #!/usr/bin/env python +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + import os, sys, locale import time diff --git a/headphones/__init__.py b/headphones/__init__.py index 793b92c0..a775099d 100644 --- a/headphones/__init__.py +++ b/headphones/__init__.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + from __future__ import with_statement import os, sys, subprocess diff --git a/headphones/albumart.py b/headphones/albumart.py index 08773870..37147be3 100644 --- a/headphones/albumart.py +++ b/headphones/albumart.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + from headphones import db def getAlbumArt(albumid): diff --git a/headphones/api.py b/headphones/api.py index 852249c9..3da1ed6b 100644 --- a/headphones/api.py +++ b/headphones/api.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + import headphones from headphones import db, mb, importer, searcher, postprocessor, versioncheck, logger diff --git a/headphones/classes.py b/headphones/classes.py index 5dc37eb6..cf6534bb 100644 --- a/headphones/classes.py +++ b/headphones/classes.py @@ -1,22 +1,21 @@ -# Author: Nic Wolfe -# URL: http://code.google.com/p/sickbeard/ +# This file is part of Headphones. # -# This file is part of Sick Beard. +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# Sick Beard is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# Sick Beard is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Sick Beard. If not, see . - +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . +######################################### +## Stolen from Sick-Beard's classes.py ## +######################################### import headphones diff --git a/headphones/common.py b/headphones/common.py index cebebcb3..c195855f 100644 --- a/headphones/common.py +++ b/headphones/common.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + ''' Created on Aug 1, 2011 @@ -159,4 +174,4 @@ ANY = Quality.combineQualities([Quality.B192, Quality.B256, Quality.B320, Qualit qualityPresets = (MP3, LOSSLESS, ANY) qualityPresetStrings = {MP3: "MP3 (All bitrates 192+)", LOSSLESS: "Lossless (flac)", - ANY: "Any"} \ No newline at end of file + ANY: "Any"} diff --git a/headphones/db.py b/headphones/db.py index 20113a1c..601b6286 100644 --- a/headphones/db.py +++ b/headphones/db.py @@ -1,4 +1,21 @@ -# Stolen from sick beards db.py. +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + +##################################### +## Stolen from Sick-Beard's db.py ## +##################################### from __future__ import with_statement diff --git a/headphones/exceptions.py b/headphones/exceptions.py index d591edff..47de6d99 100644 --- a/headphones/exceptions.py +++ b/headphones/exceptions.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + def ex(e): """ Returns a string from the exception text if it exists. diff --git a/headphones/helpers.py b/headphones/helpers.py index a6d732f2..1dbfbcda 100644 --- a/headphones/helpers.py +++ b/headphones/helpers.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + import time from operator import itemgetter import datetime diff --git a/headphones/importer.py b/headphones/importer.py index 575b5ca4..400fc303 100644 --- a/headphones/importer.py +++ b/headphones/importer.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + from lib.pyItunes import * import time import os diff --git a/headphones/lastfm.py b/headphones/lastfm.py index 84df9050..c770d187 100644 --- a/headphones/lastfm.py +++ b/headphones/lastfm.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + import urllib from xml.dom import minidom from collections import defaultdict diff --git a/headphones/librarysync.py b/headphones/librarysync.py index 900cd405..b7b102ac 100644 --- a/headphones/librarysync.py +++ b/headphones/librarysync.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + import os import glob diff --git a/headphones/logger.py b/headphones/logger.py index 758d1233..d03e13a3 100644 --- a/headphones/logger.py +++ b/headphones/logger.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + import os import threading import logging diff --git a/headphones/lyrics.py b/headphones/lyrics.py index 6ce42b57..c8eda8a6 100644 --- a/headphones/lyrics.py +++ b/headphones/lyrics.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + import re import urllib from xml.dom import minidom diff --git a/headphones/mb.py b/headphones/mb.py index 6c5a652b..a3853c23 100644 --- a/headphones/mb.py +++ b/headphones/mb.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + from __future__ import with_statement import time diff --git a/headphones/music_encoder.py b/headphones/music_encoder.py index 4c0f4d65..93b56e23 100644 --- a/headphones/music_encoder.py +++ b/headphones/music_encoder.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + import os import headphones import shutil diff --git a/headphones/notifiers.py b/headphones/notifiers.py index 047497af..695796d0 100644 --- a/headphones/notifiers.py +++ b/headphones/notifiers.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + from headphones import logger import base64 import cherrypy diff --git a/headphones/postprocessor.py b/headphones/postprocessor.py index a252273c..3a1e64c2 100644 --- a/headphones/postprocessor.py +++ b/headphones/postprocessor.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + import os import time import music_encoder diff --git a/headphones/sab.py b/headphones/sab.py index 1f5a5889..6d57214c 100644 --- a/headphones/sab.py +++ b/headphones/sab.py @@ -1,19 +1,21 @@ -# This file is part of Sick Beard. +# This file is part of Headphones. # -# Sick Beard is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# Sick Beard is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with Sick Beard. If not, see . - +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . +##################################### +## Stolen from Sick-Beard's sab.py ## +##################################### import urllib, httplib import datetime diff --git a/headphones/searcher.py b/headphones/searcher.py index 4f8166c9..73538148 100644 --- a/headphones/searcher.py +++ b/headphones/searcher.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + import urllib, urllib2, urlparse import lib.feedparser as feedparser from xml.dom import minidom diff --git a/headphones/updater.py b/headphones/updater.py index 3aa5e847..c80eec0b 100644 --- a/headphones/updater.py +++ b/headphones/updater.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + import headphones from headphones import logger, db, importer diff --git a/headphones/versioncheck.py b/headphones/versioncheck.py index 669b2e5e..a40b5e6e 100644 --- a/headphones/versioncheck.py +++ b/headphones/versioncheck.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + import platform, subprocess, re, os, urllib2, tarfile import headphones diff --git a/headphones/webserve.py b/headphones/webserve.py index 13b9c5fa..b06e9584 100644 --- a/headphones/webserve.py +++ b/headphones/webserve.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + import os import cherrypy diff --git a/headphones/webstart.py b/headphones/webstart.py index 7d0cfa73..d8e399b3 100644 --- a/headphones/webstart.py +++ b/headphones/webstart.py @@ -1,3 +1,18 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + import os import sys From b1115e748d9cd6619081604792b2d19c44989f9a Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 19 Jun 2012 13:36:50 +0530 Subject: [PATCH 05/52] Add spokenword & audiobooks to extras --- headphones/mb.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/headphones/mb.py b/headphones/mb.py index a3853c23..f1ec280c 100644 --- a/headphones/mb.py +++ b/headphones/mb.py @@ -239,7 +239,7 @@ def getArtist(artistid, extrasonly=False): includeExtras = False if includeExtras or headphones.INCLUDE_EXTRAS: - includes = ["single", "ep", "compilation", "soundtrack", "live", "remix"] + includes = ["single", "ep", "compilation", "soundtrack", "live", "remix", "spokenword", "audiobook"] for include in includes: artist = None From 8ccb2146dfe6bbaf874091ed8860a9e3a29391b3 Mon Sep 17 00:00:00 2001 From: jnikolich Date: Tue, 19 Jun 2012 14:23:36 -0400 Subject: [PATCH 06/52] Initial commit of 'init.fedora.centos.systemd' - a service unit file for systemd-based platforms --- init.fedora.centos.systemd | 66 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 init.fedora.centos.systemd diff --git a/init.fedora.centos.systemd b/init.fedora.centos.systemd new file mode 100644 index 00000000..bc1b451a --- /dev/null +++ b/init.fedora.centos.systemd @@ -0,0 +1,66 @@ +# Headphones - Automatic music downloader for SABnzbd +# +# Service Unit file for systemd system manager +# +# INSTALLATION NOTES +# +# 1. Rename this file as you want, ensuring that it ends in .service +# e.g. 'headphones.service' +# +# 2. Adjust configuration settings as required. More details in the +# "CONFIGURATION NOTES" section shown below. +# +# 3. Copy this file into your systemd service unit directory, which is +# often '/lib/systemd/system'. +# +# 4. Create any files/directories that you specified back in step #2. +# e.g. '/etc/headphones/headphones.ini' +# '/home/sabnzbd/.headphones' +# +# 5. Enable boot-time autostart with the following commands: +# systemctl daemon-reload +# systemctl enable headphones.service +# +# 6. Start now with the following command: +# systemctl start headphones.service +# +# 7. If troubleshooting startup-errors, start by checking permissions +# and ownership on the files/directories that you created in step #4. +# +# +# CONFIGURATION NOTES +# +# - The example settings in this file assume that: +# 1. You will run Headphones as user/group: sabnzbd.sabnzbd +# 2. You will either have Headphones installed as a subdirectory +# under '~sabnzbd', or that you will have a symlink under +# '~/sabnzbd' pointing to your Headphones install dir. +# 3. Your Headphones data directory and configuration file will be +# in separate locations from your Headphones install dir, to +# simplify updates. +# +# - Option names (e.g. ExecStart=, Type=) appear to be case-sensitive) +# +# - Adjust ExecStart= to point to: +# 1. Your Headphones executable, +# 2. Your config file (recommended is to put it somewhere in /etc) +# 3. Your datadir (recommended is to NOT put it in your Headphones exec dir) +# +# - Adjust User= and Group= to the user/group you want Headphones to run as. +# +# - WantedBy= specifies which target (i.e. runlevel) to start Headphones for. +# multi-user.target equates to runlevel 3 (multi-user text mode) +# graphical.target equates to runlevel 5 (multi-user X11 graphical mode) + +[Unit] +Description=Headphones - Automatic music downloader for SABnzbd + +[Service] +ExecStart=/home/sabnzbd/headphones/Headphones.py --daemon --config /etc/headphones/headphones.ini --datadir /home/sabnzbd/.headphones --nolaunch --quiet +GuessMainPID=no +Type=forking +User=sabnzbd +Group=sabnzbd + +[Install] +WantedBy=multi-user.target From a2125fce2a6e663d227785457b112c6ba3e4f916 Mon Sep 17 00:00:00 2001 From: Paperfeed Date: Wed, 20 Jun 2012 00:59:37 +0300 Subject: [PATCH 07/52] Added referer to preprocesstorrent function to fix Kat.ph torrents --- headphones/searcher.py | 50 +++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 27 deletions(-) diff --git a/headphones/searcher.py b/headphones/searcher.py index 0ed33eaf..8242e8fd 100644 --- a/headphones/searcher.py +++ b/headphones/searcher.py @@ -896,30 +896,26 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False): def preprocesstorrent(resultlist): selresult = "" for result in resultlist: - try: - if selresult == "": - selresult = result - request = urllib2.Request(result[2]) - request.add_header('Accept-encoding', 'gzip') - response = urllib2.urlopen(request) - if response.info().get('Content-Encoding') == 'gzip': - buf = StringIO( response.read()) - f = gzip.GzipFile(fileobj=buf) - torrent = f.read() - else: - torrent = response.read() - elif int(selresult[1]) < int(result[1]): - selresult = result - request = urllib2.Request(result[2]) - request.add_header('Accept-encoding', 'gzip') - response = urllib2.urlopen(request) - if response.info().get('Content-Encoding') == 'gzip': - buf = StringIO( response.read()) - f = gzip.GzipFile(fileobj=buf) - torrent = f.read() - else: - torrent = response.read() - except ExpatError: - logger.error('Unable to torrent file. Skipping.') - continue - return torrent, selresult + if selresult == "": + selresult = result + elif int(selresult[1]) < int(result[1]): # if size is lower than new result replace previous selected result (bigger size = better quality?) + selresult = result + + try: + request = urllib2.Request(selresult[2]) + request.add_header('Accept-encoding', 'gzip') + + if selresult[3] == 'Kick Ass Torrent': + request.add_header('Referer', 'http://kat.ph/') + + response = urllib2.urlopen(request) + if response.info().get('Content-Encoding') == 'gzip': + buf = StringIO(response.read()) + f = gzip.GzipFile(fileobj=buf) + torrent = f.read() + else: + torrent = response.read() + except ExpatError: + logger.error('Unable to torrent %s' % selresult[2]) + + return torrent, selresult \ No newline at end of file From b6be5f828ae09e414925d0b94724d6fc28fba2ea Mon Sep 17 00:00:00 2001 From: Paperfeed Date: Wed, 20 Jun 2012 01:43:07 +0300 Subject: [PATCH 08/52] Fix for kat.ph torrents --- headphones/searcher.py | 1 + 1 file changed, 1 insertion(+) diff --git a/headphones/searcher.py b/headphones/searcher.py index 8242e8fd..7e250d01 100644 --- a/headphones/searcher.py +++ b/headphones/searcher.py @@ -643,6 +643,7 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False): if format == "2": request = urllib2.Request(url) request.add_header('Accept-encoding', 'gzip') + request.add_header('Referer', 'http://kat.ph/') response = urllib2.urlopen(request) if response.info().get('Content-Encoding') == 'gzip': buf = StringIO( response.read()) From b4de7fe22f6c6dd8073877a913245e4fa3c6e3c8 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Thu, 21 Jun 2012 15:44:15 +0530 Subject: [PATCH 09/52] First commit for the caching mechanism --- headphones/cache.py | 216 +++++++++++++++++++++++++++++++++++++++++ headphones/webserve.py | 21 ++++ 2 files changed, 237 insertions(+) create mode 100644 headphones/cache.py diff --git a/headphones/cache.py b/headphones/cache.py new file mode 100644 index 00000000..24da24c9 --- /dev/null +++ b/headphones/cache.py @@ -0,0 +1,216 @@ +# This file is part of Headphones. +# +# Headphones is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Headphones is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Headphones. If not, see . + +import os +import glob, urllib2 + +import lib.simplejson as simplejson + +import headphones +from headphones import helpers, logger + +lastfm_apikey = "690e1ed3bc00bc91804cd8f7fe5ed6d4" + +class Cache(object): + """ + This class deals with getting, storing and serving up artwork (album + art, artist images, etc) and info/descriptions (album info, artist descrptions) + to and from the cache folder. This can be called from within a web interface, + for example, using the helper functions getInfo(id) and getArtwork(id), to utilize the cached + images rather than having to retrieve them every time the page is reloaded. + + So you can call cache.getArtwork(id) which will return an absolute path + to the image file on the local machine, or if the cache directory + doesn't exist, or can not be written to, it will return a url to the image. + + Call cache.getInfo(id) to grab the artist/album info; will return the text description + + The basic format for art in the cache is .. + and for info it is ..txt + """ + + path_to_art_cache = os.path.join(headphones.CACHE_DIR, 'artwork') + path_to_info_cache = os.path.join(headphones.CACHE_DIR, 'info') + + id = None + id_type = None # 'artist' or 'album' + + artwork_files = [] + info_files = [] + + def __init__(self): + + pass + + def _exists(self, type): + + if type == 'artwork': + + self.artwork_files = glob.glob(os.path.join(self.path_to_art_cache, self.id + '*')) + + if self.artwork_files: + return True + else: + return False + + else: + + self.info_files = glob.glob(os.path.join(self.path_to_info_cache, self.id + '*')) + + if self.info_files: + return True + else: + return False + + def _get_age(self, date): + # There's probably a better way to do this + split_date = date.split('-') + days_old = int(split_date[0])*365 + int(split_date[1])*30 + int(split_date[2]) + + return days_old + + + def _is_current(self, file): + + base_filename = os.path.basename(file) + date = base_filename.split('.')[1] + + # Calculate how old the cached file is based on todays date & file date stamp + # helpers.today() returns todays date in yyyy-mm-dd format + if self._get_age(helpers.today()) - self._get_age(date) < 30: + return True + else: + return False + + def get_artwork_from_cache(self, id, id_type): + ''' + Pass a musicbrainz id to this function, and a type (either artist or album) + ''' + + self.id = id + self.id_type = id_type + + if self._exists('artwork') and self._is_current(self.artwork_files[0]): + return self.artwork_files[0] + else: + self._update_cache() + if self._exists('artwork'): + return self.artwork_files[0] + + def get_info_from_cache(self, id, id_type): + + self.id = id + self.id_type = id_type + + if self._exists('info') and self._is_current(self.info_files[0]): + f = open(self.info_files[0], 'r').read() + return f + else: + self._update_cache() + if self._exists('info'): + f = open(self.info_files[0],'r').read() + return f + + def _update_cache(self): + ''' + Since we call the same url for both info and artwork, we'll update both at the same time + ''' + + url = "http://ws.audioscrobbler.com/2.0/?method=" + self.id_type + ".getInfo&mbid=" + self.id + "&api_key=" + lastfm_apikey + "&format=json" + + logger.debug('Retrieving artist information from: ' + url) + try: + result = urllib2.urlopen(url).read() + artist = simplejson.JSONDecoder().decode(result) + artist_bio = artist['artist']['bio']['content'] + artist_image_url = artist['artist']['image'][4]['#text'] + except: + logger.warn('Could not open url: ' + url) + return + + if artist_bio: + + # Make sure the info dir exists: + if not os.path.isdir(self.path_to_info_cache): + try: + os.makedirs(self.path_to_info_cache) + except Exception, e: + logger.error('Unable to create info cache dir. Error: ' + e) + + # Delete any old files and replace it with a new one + for info_file in self.info_files: + try: + os.remove(info_file) + except: + logger.error('Error deleting file from the cache: ' + info_file) + + bio_path = os.path.join(self.path_to_info_cache, self.id + '.' + helpers.today() + '.txt') + try: + f = open(bio_path, 'w') + f.write(artist_bio) + f.close() + except Exception, e: + logger.error('Unable to write to the cache dir: ' + e) + + if artist_image_url: + + try: + artwork = urllib2.urlopen(artist_image_url).read() + except Exception, e: + logger.error('Unable to open url "' + artist_image_url + '". Error: ' + str(e)) + + if artwork: + + # Make sure the info dir exists: + if not os.path.isdir(self.path_to_art_cache): + try: + os.makedirs(self.path_to_art_cache) + except Exception, e: + logger.error('Unable to create artwork cache dir. Error: ' + str(e)) + #Delete the old stuff + for artwork_file in self.artwork_files: + try: + os.remove(artwork_file) + except: + logger.error('Error deleting file from the cache: ' + artwork_file) + + artwork_path = os.path.join(self.path_to_art_cache, self.id + '.' + helpers.today() + '.' + artist_image_url.replace('/','%%%').replace(':','_%_')) + try: + f = open(artwork_path, 'wb') + f.write(artwork) + f.close() + except Exception, e: + logger.error('Unable to write to the cache dir: ' + str(e)) + +def getArtwork(id, id_type): + + c = Cache() + artwork_path = c.get_artwork_from_cache(id, id_type) + return artwork_path + +def getInfo(id, id_type): + + c = Cache() + info_path = c.get_info_from_cache(id, id_type) + return info_path + +def getArtworkURL(id, id_type): + + c = Cache() + artwork_path = c.get_artwork_from_cache(id, id_type) + filename = os.path.basename(artwork_path) + encoded_url = filename.split('.')[2:] + normal_url = encoded_url.replace('%%%','/').replace('_%_',':') + return normal_url diff --git a/headphones/webserve.py b/headphones/webserve.py index b06e9584..da6bf2e1 100644 --- a/headphones/webserve.py +++ b/headphones/webserve.py @@ -591,3 +591,24 @@ class WebInterface(object): return data api.exposed = True + + def getInfo(self, id, id_type): + + from headphones import cache + return cache.getInfo(id, id_type) + + getInfo.exposed = True + + def getArtwork(self, id, id_type): + + from headphones import cache + return cache.getArtwork(id, id_type) + + getArtwork.exposed = True + + def getArtworkURL(self,id, id_type): + + from headphones import cache + return cache.getArtworkURL(id, id_type) + + getArtworkURL.exposed = True From cd2bec3fe4ce5e0f78e0251efb913371a47a9d85 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Thu, 21 Jun 2012 15:50:27 +0530 Subject: [PATCH 10/52] A few changes to get the getArtistURL function working properly --- headphones/cache.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/headphones/cache.py b/headphones/cache.py index 24da24c9..69c367fb 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -211,6 +211,6 @@ def getArtworkURL(id, id_type): c = Cache() artwork_path = c.get_artwork_from_cache(id, id_type) filename = os.path.basename(artwork_path) - encoded_url = filename.split('.')[2:] + encoded_url = '.'.join(filename.split('.')[2:]) normal_url = encoded_url.replace('%%%','/').replace('_%_',':') return normal_url From 4809562674912790624bca36f66557a56586f37b Mon Sep 17 00:00:00 2001 From: rembo10 Date: Thu, 21 Jun 2012 16:52:02 +0530 Subject: [PATCH 11/52] MoNow storing ImageURL to the database so it can be served through the api. Files are writen as UTF-8 --- headphones/__init__.py | 16 +++++++-- headphones/cache.py | 81 +++++++++++++++++++++++++----------------- 2 files changed, 61 insertions(+), 36 deletions(-) diff --git a/headphones/__init__.py b/headphones/__init__.py index a775099d..49548405 100644 --- a/headphones/__init__.py +++ b/headphones/__init__.py @@ -672,8 +672,8 @@ def dbcheck(): conn=sqlite3.connect(DB_FILE) c=conn.cursor() - c.execute('CREATE TABLE IF NOT EXISTS artists (ArtistID TEXT UNIQUE, ArtistName TEXT, ArtistSortName TEXT, DateAdded TEXT, Status TEXT, IncludeExtras INTEGER, LatestAlbum TEXT, ReleaseDate TEXT, AlbumID TEXT, HaveTracks INTEGER, TotalTracks INTEGER, LastUpdated 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, Type TEXT)') + c.execute('CREATE TABLE IF NOT EXISTS artists (ArtistID TEXT UNIQUE, ArtistName TEXT, ArtistSortName TEXT, DateAdded TEXT, Status TEXT, IncludeExtras INTEGER, LatestAlbum TEXT, ReleaseDate TEXT, AlbumID TEXT, HaveTracks INTEGER, TotalTracks INTEGER, LastUpdated TEXT, ArtworkURL 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, Type TEXT, ArtworkURL TEXT)') c.execute('CREATE TABLE IF NOT EXISTS tracks (ArtistID TEXT, ArtistName TEXT, AlbumTitle TEXT, AlbumASIN TEXT, AlbumID TEXT, TrackTitle TEXT, TrackDuration, TrackID TEXT, TrackNumber INTEGER, Location TEXT, BitRate INTEGER, CleanName TEXT, Format TEXT)') c.execute('CREATE TABLE IF NOT EXISTS snatched (AlbumID TEXT, Title TEXT, Size INTEGER, URL TEXT, DateAdded TEXT, Status TEXT, FolderName TEXT)') c.execute('CREATE TABLE IF NOT EXISTS have (ArtistName TEXT, AlbumTitle TEXT, TrackNumber TEXT, TrackTitle TEXT, TrackLength TEXT, BitRate TEXT, Genre TEXT, Date TEXT, TrackID TEXT, Location TEXT, CleanName TEXT, Format TEXT)') @@ -767,7 +767,17 @@ def dbcheck(): try: c.execute('SELECT LastUpdated from artists') except sqlite3.OperationalError: - c.execute('ALTER TABLE artists ADD COLUMN LastUpdated TEXT DEFAULT NULL') + c.execute('ALTER TABLE artists ADD COLUMN LastUpdated TEXT DEFAULT NULL') + + try: + c.execute('SELECT ArtworkURL from artists') + except sqlite3.OperationalError: + c.execute('ALTER TABLE artists ADD COLUMN ArtworkURL TEXT DEFAULT NULL') + + try: + c.execute('SELECT ArtworkURL from albums') + except sqlite3.OperationalError: + c.execute('ALTER TABLE albums ADD COLUMN ArtworkURL TEXT DEFAULT NULL') conn.commit() c.close() diff --git a/headphones/cache.py b/headphones/cache.py index 69c367fb..405c6881 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -19,7 +19,7 @@ import glob, urllib2 import lib.simplejson as simplejson import headphones -from headphones import helpers, logger +from headphones import db, helpers, logger lastfm_apikey = "690e1ed3bc00bc91804cd8f7fe5ed6d4" @@ -116,38 +116,55 @@ class Cache(object): if self._exists('info') and self._is_current(self.info_files[0]): f = open(self.info_files[0], 'r').read() - return f + return f.decode('utf-8') else: self._update_cache() if self._exists('info'): f = open(self.info_files[0],'r').read() - return f + return f.decode('utf-8') def _update_cache(self): ''' Since we call the same url for both info and artwork, we'll update both at the same time ''' - url = "http://ws.audioscrobbler.com/2.0/?method=" + self.id_type + ".getInfo&mbid=" + self.id + "&api_key=" + lastfm_apikey + "&format=json" + # Since lastfm uses release ids rather than release group ids for albums, we have to do a artist + album search for albums + if self.id_type == 'artist': + url = "http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&mbid=" + self.id + "&api_key=" + lastfm_apikey + "&format=json" + logger.debug('Retrieving artist information from: ' + url) + + try: + result = urllib2.urlopen(url).read() + data = simplejson.JSONDecoder().decode(result) + info = artist['artist']['bio']['content'] + image_url = artist['artist']['image'][-1]['#text'] + except: + logger.warn('Could not open url: ' + url) + return + + else: + myDB = db.DBConnection() + dbartist = myDB.action('SELECT ArtistName, AlbumTitle FROM albums WHERE AlbumID=?', [self.id]).fetchone() + url = "http://ws.audioscrobbler.com/2.0/?method=album.getInfo&api_key=" + lastfm_apikey + "&artist="+ dbartist['ArtistName'] +"&album="+ dbartist['AlbumTitle'] +"&format=json" + + logger.debug('Retrieving artist information from: ' + url) + try: + result = urllib2.urlopen(url).read() + data = simplejson.JSONDecoder().decode(result) + info = data['album']['wiki']['content'] + image_url = data['album']['image'][-1]['#text'] + except: + logger.warn('Could not open url: ' + url) + return - logger.debug('Retrieving artist information from: ' + url) - try: - result = urllib2.urlopen(url).read() - artist = simplejson.JSONDecoder().decode(result) - artist_bio = artist['artist']['bio']['content'] - artist_image_url = artist['artist']['image'][4]['#text'] - except: - logger.warn('Could not open url: ' + url) - return - - if artist_bio: + if info: # Make sure the info dir exists: if not os.path.isdir(self.path_to_info_cache): try: os.makedirs(self.path_to_info_cache) except Exception, e: - logger.error('Unable to create info cache dir. Error: ' + e) + logger.error('Unable to create info cache dir. Error: ' + str(e)) # Delete any old files and replace it with a new one for info_file in self.info_files: @@ -156,20 +173,27 @@ class Cache(object): except: logger.error('Error deleting file from the cache: ' + info_file) - bio_path = os.path.join(self.path_to_info_cache, self.id + '.' + helpers.today() + '.txt') + info_file_path = os.path.join(self.path_to_info_cache, self.id + '.' + helpers.today() + '.txt') try: - f = open(bio_path, 'w') - f.write(artist_bio) + f = open(info_file_path, 'w') + f.write(info.encode('utf-8')) f.close() except Exception, e: - logger.error('Unable to write to the cache dir: ' + e) + logger.error('Unable to write to the cache dir: ' + str(e)) - if artist_image_url: + if image_url: + + myDB = db.DBConnection() + + if self.id_type == 'artist': + myDB.action('UPDATE artists SET ArtworkURL=? WHERE ArtistID=?', [image_url, self.id]) + else: + myDB.action('UPDATE albums SET ArtworkURL=? WHERE AlbumID=?', [image_url, self.id]) try: - artwork = urllib2.urlopen(artist_image_url).read() + artwork = urllib2.urlopen(image_url).read() except Exception, e: - logger.error('Unable to open url "' + artist_image_url + '". Error: ' + str(e)) + logger.error('Unable to open url "' + image_url + '". Error: ' + str(e)) if artwork: @@ -186,7 +210,7 @@ class Cache(object): except: logger.error('Error deleting file from the cache: ' + artwork_file) - artwork_path = os.path.join(self.path_to_art_cache, self.id + '.' + helpers.today() + '.' + artist_image_url.replace('/','%%%').replace(':','_%_')) + artwork_path = os.path.join(self.path_to_art_cache, self.id + '.' + helpers.today() + '.' + image_url.replace('/','%%%').replace(':','_%_')) try: f = open(artwork_path, 'wb') f.write(artwork) @@ -205,12 +229,3 @@ def getInfo(id, id_type): c = Cache() info_path = c.get_info_from_cache(id, id_type) return info_path - -def getArtworkURL(id, id_type): - - c = Cache() - artwork_path = c.get_artwork_from_cache(id, id_type) - filename = os.path.basename(artwork_path) - encoded_url = '.'.join(filename.split('.')[2:]) - normal_url = encoded_url.replace('%%%','/').replace('_%_',':') - return normal_url From 7df4c6d9e422b6f089915b8bf23ea86e87d5b261 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Thu, 21 Jun 2012 20:36:13 +0530 Subject: [PATCH 12/52] Fixed the info and image_url variables. Removed url from filenames --- headphones/cache.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/headphones/cache.py b/headphones/cache.py index 405c6881..9b30cba6 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -37,7 +37,7 @@ class Cache(object): Call cache.getInfo(id) to grab the artist/album info; will return the text description - The basic format for art in the cache is .. + The basic format for art in the cache is .. and for info it is ..txt """ @@ -136,8 +136,8 @@ class Cache(object): try: result = urllib2.urlopen(url).read() data = simplejson.JSONDecoder().decode(result) - info = artist['artist']['bio']['content'] - image_url = artist['artist']['image'][-1]['#text'] + info = data['artist']['bio']['content'] + image_url = data['artist']['image'][-1]['#text'] except: logger.warn('Could not open url: ' + url) return @@ -210,7 +210,9 @@ class Cache(object): except: logger.error('Error deleting file from the cache: ' + artwork_file) - artwork_path = os.path.join(self.path_to_art_cache, self.id + '.' + helpers.today() + '.' + image_url.replace('/','%%%').replace(':','_%_')) + ext = os.path.splitext(image_url)[1] + + artwork_path = os.path.join(self.path_to_art_cache, self.id + '.' + helpers.today() + ext) try: f = open(artwork_path, 'wb') f.write(artwork) From 8a64187c6b2724571178e9faee6ad6cac3f39ce4 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Thu, 21 Jun 2012 22:09:07 +0530 Subject: [PATCH 13/52] getArtwork now returns a file:///path-to-file or a http://image-url (the latter if, for example, the artwork cache dir can't be created. getInfo will return the description/info as well, even if the file can't be created --- headphones/cache.py | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/headphones/cache.py b/headphones/cache.py index 9b30cba6..e8d36c05 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -50,6 +50,11 @@ class Cache(object): artwork_files = [] info_files = [] + artwork_errors = False + info_errors = False + info = None + artwork_url = None + def __init__(self): pass @@ -106,6 +111,9 @@ class Cache(object): return self.artwork_files[0] else: self._update_cache() + + if self.artwork_errors: + return self.artwork_url if self._exists('artwork'): return self.artwork_files[0] @@ -119,6 +127,10 @@ class Cache(object): return f.decode('utf-8') else: self._update_cache() + + if self.info_errors: + return self.info + if self._exists('info'): f = open(self.info_files[0],'r').read() return f.decode('utf-8') @@ -165,6 +177,8 @@ class Cache(object): os.makedirs(self.path_to_info_cache) except Exception, e: logger.error('Unable to create info cache dir. Error: ' + str(e)) + self.info_errors = True + self.info = info # Delete any old files and replace it with a new one for info_file in self.info_files: @@ -180,6 +194,8 @@ class Cache(object): f.close() except Exception, e: logger.error('Unable to write to the cache dir: ' + str(e)) + self.info_errors = True + self.info = info if image_url: @@ -203,6 +219,9 @@ class Cache(object): os.makedirs(self.path_to_art_cache) except Exception, e: logger.error('Unable to create artwork cache dir. Error: ' + str(e)) + self.artwork_errors = True + self.artwork_url = image_url + #Delete the old stuff for artwork_file in self.artwork_files: try: @@ -219,15 +238,21 @@ class Cache(object): f.close() except Exception, e: logger.error('Unable to write to the cache dir: ' + str(e)) + self.artwork_errors = True + self.artwork_url = image_url def getArtwork(id, id_type): c = Cache() artwork_path = c.get_artwork_from_cache(id, id_type) - return artwork_path + + if artwork_path.startswith('http://'): + return artwork_path + else: + return "file:///" + artwork_path def getInfo(id, id_type): c = Cache() - info_path = c.get_info_from_cache(id, id_type) - return info_path + info = c.get_info_from_cache(id, id_type) + return info From 63e4dc65c28d98adb1d92b859575a1cf4e37e18b Mon Sep 17 00:00:00 2001 From: rembo10 Date: Thu, 21 Jun 2012 22:50:51 +0530 Subject: [PATCH 14/52] Updated versioncheck to correctly identify the HenryFord win32 build --- headphones/versioncheck.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/headphones/versioncheck.py b/headphones/versioncheck.py index a40b5e6e..429ec8b9 100644 --- a/headphones/versioncheck.py +++ b/headphones/versioncheck.py @@ -62,7 +62,7 @@ def runGit(args): def getVersion(): - if version.HEADPHONES_VERSION.startswith('build '): + if version.HEADPHONES_VERSION.startswith('win32build'): headphones.INSTALL_TYPE = 'win' From 517d51a2109a22f589faf4447289bf7275c8fdaf Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 10:39:15 +0530 Subject: [PATCH 15/52] Updated .gitignore to ignore cached files --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 54c43436..74e29c78 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ *.db-journal *.ini logs/* +cache/* # OS generated files # ###################### From 4a12307cb8d7b991786dd5de647fb072c9131c7e Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 11:04:39 +0530 Subject: [PATCH 16/52] Modifieded the getArtwork and getInfo functions so you can now just pass an ArtistID or AlbumID without having to specify the type as well. Also - changed the error catching when opening the url & parsing the data --- headphones/cache.py | 73 ++++++++++++++++++++++++++++-------------- headphones/webserve.py | 15 +++------ 2 files changed, 53 insertions(+), 35 deletions(-) diff --git a/headphones/cache.py b/headphones/cache.py index e8d36c05..6bbabfd1 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -99,28 +99,37 @@ class Cache(object): else: return False - def get_artwork_from_cache(self, id, id_type): + def get_artwork_from_cache(self, ArtistID=None, AlbumID=None): ''' - Pass a musicbrainz id to this function, and a type (either artist or album) + Pass a musicbrainz id to this function (either ArtistID or AlbumID) ''' - - self.id = id - self.id_type = id_type + if ArtistID: + self.id = ArtistID + self.id_type = 'artist' + else: + self.id = AlbumID + self.id_type = 'album' if self._exists('artwork') and self._is_current(self.artwork_files[0]): return self.artwork_files[0] else: self._update_cache() - - if self.artwork_errors: + # If we failed to get artwork, either return the url or the older file + if self.artwork_errors and self.artwork_url: return self.artwork_url - if self._exists('artwork'): + elif self._exists('artwork'): return self.artwork_files[0] + else: + return None - def get_info_from_cache(self, id, id_type): + def get_info_from_cache(self, ArtistID=None, AlbumID=None): - self.id = id - self.id_type = id_type + if ArtistID: + self.id = ArtistID + self.id_type = 'artist' + else: + self.id = AlbumID + self.id_type = 'album' if self._exists('info') and self._is_current(self.info_files[0]): f = open(self.info_files[0], 'r').read() @@ -128,12 +137,15 @@ class Cache(object): else: self._update_cache() - if self.info_errors: + if self.info_errors and self.info: return self.info - if self._exists('info'): + elif self._exists('info'): f = open(self.info_files[0],'r').read() return f.decode('utf-8') + + else: + return None def _update_cache(self): ''' @@ -147,12 +159,19 @@ class Cache(object): try: result = urllib2.urlopen(url).read() - data = simplejson.JSONDecoder().decode(result) - info = data['artist']['bio']['content'] - image_url = data['artist']['image'][-1]['#text'] except: logger.warn('Could not open url: ' + url) - return + return + + if result: + + try: + data = simplejson.JSONDecoder().decode(result) + info = data['artist']['bio']['content'] + image_url = data['artist']['image'][-1]['#text'] + except: + logger.warn('Could not parse data from url: ' + url) + return else: myDB = db.DBConnection() @@ -162,12 +181,18 @@ class Cache(object): logger.debug('Retrieving artist information from: ' + url) try: result = urllib2.urlopen(url).read() - data = simplejson.JSONDecoder().decode(result) - info = data['album']['wiki']['content'] - image_url = data['album']['image'][-1]['#text'] except: logger.warn('Could not open url: ' + url) return + + if result: + try: + data = simplejson.JSONDecoder().decode(result) + info = data['album']['wiki']['content'] + image_url = data['album']['image'][-1]['#text'] + except: + logger.warn('Could not parse data from url: ' + url) + return if info: @@ -241,18 +266,18 @@ class Cache(object): self.artwork_errors = True self.artwork_url = image_url -def getArtwork(id, id_type): +def getArtwork(ArtistID=None, AlbumID=None): c = Cache() - artwork_path = c.get_artwork_from_cache(id, id_type) + artwork_path = c.get_artwork_from_cache(ArtistID, AlbumID) if artwork_path.startswith('http://'): return artwork_path else: return "file:///" + artwork_path -def getInfo(id, id_type): +def getInfo(ArtistID=None, AlbumID=None): c = Cache() - info = c.get_info_from_cache(id, id_type) + info = c.get_info_from_cache(ArtistID, AlbumID) return info diff --git a/headphones/webserve.py b/headphones/webserve.py index da6bf2e1..45d5b3ea 100644 --- a/headphones/webserve.py +++ b/headphones/webserve.py @@ -592,23 +592,16 @@ class WebInterface(object): api.exposed = True - def getInfo(self, id, id_type): + def getInfo(self, ArtistID=None, AlbumID=None): from headphones import cache - return cache.getInfo(id, id_type) + return cache.getInfo(ArtistID, AlbumID) getInfo.exposed = True - def getArtwork(self, id, id_type): + def getArtwork(self, ArtistID=None, AlbumID=None): from headphones import cache - return cache.getArtwork(id, id_type) + return cache.getArtwork(ArtistID, AlbumID) getArtwork.exposed = True - - def getArtworkURL(self,id, id_type): - - from headphones import cache - return cache.getArtworkURL(id, id_type) - - getArtworkURL.exposed = True From a2563458f1690cc013aec461df76a05e3444047d Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 11:32:15 +0530 Subject: [PATCH 17/52] Catch KeyErrors if the data doesn't exist, urlencode the parameters --- headphones/cache.py | 46 +++++++++++++++++++++++++++++++++++++-------- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/headphones/cache.py b/headphones/cache.py index 6bbabfd1..29564756 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -14,7 +14,7 @@ # along with Headphones. If not, see . import os -import glob, urllib2 +import glob, urllib, urllib2 import lib.simplejson as simplejson @@ -154,7 +154,14 @@ class Cache(object): # Since lastfm uses release ids rather than release group ids for albums, we have to do a artist + album search for albums if self.id_type == 'artist': - url = "http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&mbid=" + self.id + "&api_key=" + lastfm_apikey + "&format=json" + + params = { "method": "artist.getInfo", + "api_key": lastfm_apikey, + "mbid": self.id, + "format": "json" + } + + url = "http://ws.audioscrobbler.com/2.0/?" + urllib.urlencode(params) logger.debug('Retrieving artist information from: ' + url) try: @@ -167,16 +174,32 @@ class Cache(object): try: data = simplejson.JSONDecoder().decode(result) - info = data['artist']['bio']['content'] - image_url = data['artist']['image'][-1]['#text'] except: logger.warn('Could not parse data from url: ' + url) return + try: + info = data['artist']['bio']['content'] + except KeyError: + logger.debug('No artist bio found on url: ' + url) + info = None + try: + image_url = data['artist']['image'][-1]['#text'] + except KeyError: + logger.debug('No artist image found on url: ' + url) + image_url = None else: myDB = db.DBConnection() dbartist = myDB.action('SELECT ArtistName, AlbumTitle FROM albums WHERE AlbumID=?', [self.id]).fetchone() - url = "http://ws.audioscrobbler.com/2.0/?method=album.getInfo&api_key=" + lastfm_apikey + "&artist="+ dbartist['ArtistName'] +"&album="+ dbartist['AlbumTitle'] +"&format=json" + + params = { "method": "album.getInfo", + "api_key": lastfm_apikey, + "artist": dbartist['ArtistName'], + "album": dbartist['AlbumTitle'], + "format": "json" + } + + url = "http://ws.audioscrobbler.com/2.0/?" + urllib.urlencode(params) logger.debug('Retrieving artist information from: ' + url) try: @@ -188,12 +211,19 @@ class Cache(object): if result: try: data = simplejson.JSONDecoder().decode(result) - info = data['album']['wiki']['content'] - image_url = data['album']['image'][-1]['#text'] except: logger.warn('Could not parse data from url: ' + url) return - + try: + info = data['album']['wiki']['content'] + except KeyError: + logger.debug('No album infomation found from: ' + url) + info = None + try: + image_url = data['album']['image'][-1]['#text'] + except KeyError: + logger.debug('No album image link found on url: ' + url) + image_url = None if info: # Make sure the info dir exists: From 20cf3930b2e603f829ae8ac709828fc854729266 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 11:37:25 +0530 Subject: [PATCH 18/52] Covert unicode artist/album strings to utf-8 before urlencoding --- headphones/cache.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/headphones/cache.py b/headphones/cache.py index 29564756..f227910e 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -194,8 +194,8 @@ class Cache(object): params = { "method": "album.getInfo", "api_key": lastfm_apikey, - "artist": dbartist['ArtistName'], - "album": dbartist['AlbumTitle'], + "artist": dbartist['ArtistName'].encode('utf-8'), + "album": dbartist['AlbumTitle'].encode('utf-8'), "format": "json" } From 0cfaf27b0f04c0ebd97da638236570d115cdc739 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 13:49:18 +0530 Subject: [PATCH 19/52] Get a list of all artwork and info files no matter if it's an artwork or info check --- headphones/cache.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/headphones/cache.py b/headphones/cache.py index f227910e..a86c74f7 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -60,25 +60,24 @@ class Cache(object): pass def _exists(self, type): - + + self.artwork_files = glob.glob(os.path.join(self.path_to_art_cache, self.id + '*')) + self.info_files = glob.glob(os.path.join(self.path_to_info_cache, self.id + '*')) + if type == 'artwork': - - self.artwork_files = glob.glob(os.path.join(self.path_to_art_cache, self.id + '*')) - + if self.artwork_files: return True else: return False - + else: - self.info_files = glob.glob(os.path.join(self.path_to_info_cache, self.id + '*')) - if self.info_files: return True else: return False - + def _get_age(self, date): # There's probably a better way to do this split_date = date.split('-') From 1c8699f6c200ca1efe3961cc4b69cf65205bf0f6 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 14:17:09 +0530 Subject: [PATCH 20/52] Write an empty txt file if the link doesn't have any bio/description so we don't keep checking every time --- headphones/cache.py | 43 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/headphones/cache.py b/headphones/cache.py index a86c74f7..11eb489f 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -45,7 +45,8 @@ class Cache(object): path_to_info_cache = os.path.join(headphones.CACHE_DIR, 'info') id = None - id_type = None # 'artist' or 'album' + id_type = None # 'artist' or 'album' - set automatically depending on whether ArtistID or AlbumID is passed + query_type = None # 'artwork' or 'info' - set automatically artwork_files = [] info_files = [] @@ -102,6 +103,9 @@ class Cache(object): ''' Pass a musicbrainz id to this function (either ArtistID or AlbumID) ''' + + self.query_type = 'artwork' + if ArtistID: self.id = ArtistID self.id_type = 'artist' @@ -123,6 +127,8 @@ class Cache(object): def get_info_from_cache(self, ArtistID=None, AlbumID=None): + self.query_type = 'info' + if ArtistID: self.id = ArtistID self.id_type = 'artist' @@ -250,8 +256,40 @@ class Cache(object): logger.error('Unable to write to the cache dir: ' + str(e)) self.info_errors = True self.info = info + + # If there is no info, we should either write an empty file, or make an older file current + # just so it doesn't check it every time + else: + + new_info_file_path = os.path.join(self.path_to_info_cache, self.id + '.' + helpers.today() + '.txt') + + if len(self.info_files) == 1: + try: + os.rename(self.info_files[0], new_info_file_path) + except Exception, e: + logger.warn('Error renaming cached info file: ' + str(e)) + + elif len(self.info_files) > 1: + for info_file in self.info_files[1:]: + try: + os.remove(info_file) + except Exception, e: + logger.warn('Error removing cached info file "' + info_file + '". Error: ' + str(e)) + + try: + os.rename(self.info_files[0], new_info_file_path) + except Exception, e: + logger.warn('Error renaming cached info file: ' + str(e)) + + else: + f = open(new_info_file_path, 'w') + f.close() if image_url: + + # If we're just grabbing an info file, no need to open the actual image_url unless it's outdated + if self.query_type == 'info' and self.artwork_files and self._is_current(self.artwork_files[0]): + return myDB = db.DBConnection() @@ -264,6 +302,7 @@ class Cache(object): artwork = urllib2.urlopen(image_url).read() except Exception, e: logger.error('Unable to open url "' + image_url + '". Error: ' + str(e)) + artwork = None if artwork: @@ -294,7 +333,7 @@ class Cache(object): logger.error('Unable to write to the cache dir: ' + str(e)) self.artwork_errors = True self.artwork_url = image_url - + def getArtwork(ArtistID=None, AlbumID=None): c = Cache() From 2c208ea15bd94a7750fd3c44b10af3439f32e8d7 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 14:31:55 +0530 Subject: [PATCH 21/52] Fix for getArtwork if no path (either file path or url) could be retrieved --- headphones/cache.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/headphones/cache.py b/headphones/cache.py index 11eb489f..1144a0f7 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -339,6 +339,9 @@ def getArtwork(ArtistID=None, AlbumID=None): c = Cache() artwork_path = c.get_artwork_from_cache(ArtistID, AlbumID) + if not artwork_path: + return None + if artwork_path.startswith('http://'): return artwork_path else: @@ -348,4 +351,8 @@ def getInfo(ArtistID=None, AlbumID=None): c = Cache() info = c.get_info_from_cache(ArtistID, AlbumID) + + if not info: + return None + return info From 95cadfac930643cd0c75f36e50aa4052bdf0e23e Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 16:25:31 +0530 Subject: [PATCH 22/52] Return properly formatted local image path --- headphones/cache.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/headphones/cache.py b/headphones/cache.py index 1144a0f7..067ac7a8 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -345,7 +345,7 @@ def getArtwork(ArtistID=None, AlbumID=None): if artwork_path.startswith('http://'): return artwork_path else: - return "file:///" + artwork_path + return "file://" + urllib.quote(artwork_path) def getInfo(ArtistID=None, AlbumID=None): From e27defe769c0256ecfdbe558f1a6c1743adcfeeb Mon Sep 17 00:00:00 2001 From: Ade Date: Fri, 22 Jun 2012 23:37:38 +1200 Subject: [PATCH 23/52] Get torrent folder name from the .torrent file --- headphones/bencode.py | 131 +++++++++++++++++++++++++++++++++++++++++ headphones/searcher.py | 14 +++-- 2 files changed, 140 insertions(+), 5 deletions(-) create mode 100644 headphones/bencode.py diff --git a/headphones/bencode.py b/headphones/bencode.py new file mode 100644 index 00000000..3181ee1c --- /dev/null +++ b/headphones/bencode.py @@ -0,0 +1,131 @@ +# Got this from here: https://gist.github.com/1126793 + +# The contents of this file are subject to the Python Software Foundation +# License Version 2.3 (the License). You may not copy or use this file, in +# either source code or executable form, except in compliance with the License. +# You may obtain a copy of the License at http://www.python.org/license. +# +# Software distributed under the License is distributed on an AS IS basis, +# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License +# for the specific language governing rights and limitations under the +# License. + +# Written by Petru Paler + +# Minor modifications made by Andrew Resch to replace the BTFailure errors with Exceptions + +def decode_int(x, f): + f += 1 + newf = x.index('e', f) + n = int(x[f:newf]) + if x[f] == '-': + if x[f + 1] == '0': + raise ValueError + elif x[f] == '0' and newf != f+1: + raise ValueError + return (n, newf+1) + +def decode_string(x, f): + colon = x.index(':', f) + n = int(x[f:colon]) + if x[f] == '0' and colon != f+1: + raise ValueError + colon += 1 + return (x[colon:colon+n], colon+n) + +def decode_list(x, f): + r, f = [], f+1 + while x[f] != 'e': + v, f = decode_func[x[f]](x, f) + r.append(v) + return (r, f + 1) + +def decode_dict(x, f): + r, f = {}, f+1 + while x[f] != 'e': + k, f = decode_string(x, f) + r[k], f = decode_func[x[f]](x, f) + return (r, f + 1) + +decode_func = {} +decode_func['l'] = decode_list +decode_func['d'] = decode_dict +decode_func['i'] = decode_int +decode_func['0'] = decode_string +decode_func['1'] = decode_string +decode_func['2'] = decode_string +decode_func['3'] = decode_string +decode_func['4'] = decode_string +decode_func['5'] = decode_string +decode_func['6'] = decode_string +decode_func['7'] = decode_string +decode_func['8'] = decode_string +decode_func['9'] = decode_string + +def bdecode(x): + try: + r, l = decode_func[x[0]](x, 0) + except (IndexError, KeyError, ValueError): + raise Exception("not a valid bencoded string") + + return r + +from types import StringType, IntType, LongType, DictType, ListType, TupleType + + +class Bencached(object): + + __slots__ = ['bencoded'] + + def __init__(self, s): + self.bencoded = s + +def encode_bencached(x,r): + r.append(x.bencoded) + +def encode_int(x, r): + r.extend(('i', str(x), 'e')) + +def encode_bool(x, r): + if x: + encode_int(1, r) + else: + encode_int(0, r) + +def encode_string(x, r): + r.extend((str(len(x)), ':', x)) + +def encode_list(x, r): + r.append('l') + for i in x: + encode_func[type(i)](i, r) + r.append('e') + +def encode_dict(x,r): + r.append('d') + ilist = x.items() + ilist.sort() + for k, v in ilist: + r.extend((str(len(k)), ':', k)) + encode_func[type(v)](v, r) + r.append('e') + +encode_func = {} +encode_func[Bencached] = encode_bencached +encode_func[IntType] = encode_int +encode_func[LongType] = encode_int +encode_func[StringType] = encode_string +encode_func[ListType] = encode_list +encode_func[TupleType] = encode_list +encode_func[DictType] = encode_dict + +try: + from types import BooleanType + encode_func[BooleanType] = encode_bool +except ImportError: + pass + +def bencode(x): + r = [] + encode_func[type(x)](x, r) + return ''.join(r) diff --git a/headphones/searcher.py b/headphones/searcher.py index 0ed33eaf..3f1176d8 100644 --- a/headphones/searcher.py +++ b/headphones/searcher.py @@ -11,6 +11,8 @@ import string import headphones, exceptions from headphones import logger, db, helpers, classes, sab +import bencode + class NewzbinDownloader(urllib.FancyURLopener): def __init__(self): @@ -879,15 +881,17 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False): elif headphones.TORRENTBLACKHOLE_DIR != "": + # Get torrent name from .torrent, this is usually used by the torrent client as the folder name + torrent_name = torrent_folder_name + '.torrent' download_path = os.path.join(headphones.TORRENTBLACKHOLE_DIR, torrent_name) try: - f = open(download_path, 'wb') - f.write(data) - f.close() - logger.info('File saved to: %s' % torrent_name) + torrent_file = open(download_path, 'rb').read() + torrent_info = bencode.bdecode(torrent_file) + torrent_folder_name = torrent_info['info'].get('name','') + logger.info('Torrent folder name: %s' % torrent_folder_name) except Exception, e: - logger.error('Couldn\'t write Torrent file: %s' % e) + logger.error('Couldn\'t get name from Torrent file: %s' % e) break myDB.action('UPDATE albums SET status = "Snatched" WHERE AlbumID=?', [albums[2]]) From 9866f8b4ea0fb4c6e8d4996db7ff750ff94d353a Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 17:13:37 +0530 Subject: [PATCH 24/52] Serve cached content up through cherrypy. Images/info files available through 'cache/{artwork,info}/..' --- headphones/webstart.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/headphones/webstart.py b/headphones/webstart.py index d8e399b3..b3659f55 100644 --- a/headphones/webstart.py +++ b/headphones/webstart.py @@ -56,6 +56,10 @@ def initialize(options={}): '/favicon.ico':{ 'tools.staticfile.on': True, 'tools.staticfile.filename': "images/favicon.ico" + }, + '/cache':{ + 'tools.staticdir.on': True, + 'tools.staticdir.dir': headphones.CACHE_DIR } } From fe472ecd082b18546ee93a38ecefc4d63ed3c2e0 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 17:21:44 +0530 Subject: [PATCH 25/52] Modified getArtwork to return a relative path to the cached image --- headphones/cache.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/headphones/cache.py b/headphones/cache.py index 067ac7a8..2e646c0d 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -345,7 +345,7 @@ def getArtwork(ArtistID=None, AlbumID=None): if artwork_path.startswith('http://'): return artwork_path else: - return "file://" + urllib.quote(artwork_path) + return "cache" + artwork_path[len(headphones.CACHE_DIR):] def getInfo(ArtistID=None, AlbumID=None): From 6b5c8d55a657a5e6ce1d895dc2ad7cee1149ba8f Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 17:55:55 +0530 Subject: [PATCH 26/52] Updated api commands and API_REFERENCE to include new getArtistArt, getAlbumArt, getArtistInfo & getAlbumInfo commands --- apireference => API_REFERENCE | 12 +++++++--- headphones/api.py | 44 +++++++++++++++++++++++++++++++++-- 2 files changed, 51 insertions(+), 5 deletions(-) rename apireference => API_REFERENCE (82%) diff --git a/apireference b/API_REFERENCE similarity index 82% rename from apireference rename to API_REFERENCE index bc2793ca..62f28d5d 100644 --- a/apireference +++ b/API_REFERENCE @@ -12,9 +12,9 @@ $commands¶meters[&optionalparameters]: getIndex (fetch data from index page. Returns: ArtistName, ArtistSortName, ArtistID, Status, DateAdded, [LatestAlbum, ReleaseDate, AlbumID], HaveTracks, TotalTracks, - IncludeExtras) + IncludeExtras, LastUpdated, ArtworkURL: a remote url to the artwork. To get the cached image path, see getArtistArt command) -getArtist&id=$artistid (fetch artist data. returns the artist object (see above) and album info: Status, AlbumASIN, DateAdded, AlbumTitle, ArtistName, ReleaseDate, AlbumID, ArtistID, Type) +getArtist&id=$artistid (fetch artist data. returns the artist object (see above) and album info: Status, AlbumASIN, DateAdded, AlbumTitle, ArtistName, ReleaseDate, AlbumID, ArtistID, Type, ArtworkURL: hosted image path. For cached image, see getAlbumArt command) getAlbum&id=$albumid (fetch data from album page. Returns the album object, a description object and a tracks object. Tracks contain: AlbumASIN, AlbumTitle, TrackID, Format, TrackDuration (ms), ArtistName, TrackTitle, AlbumID, ArtistID, Location, TrackNumber, CleanName (stripped of punctuation /styling), BitRate) @@ -52,4 +52,10 @@ checkGithub (updates the version information above and returns getVersion data) shutdown (shut down headphones) restart (restart headphones) -update (update headphones - you may want to check the install type in get version and not allow this if type==exe) \ No newline at end of file +update (update headphones - you may want to check the install type in get version and not allow this if type==exe) + +getArtistArt&id=$artistid (Returns either a relative path to the cached image, or a remote url if the image can't be saved to the cache dir) +getAlbumArt&id=$albumid (see above) + +getArtistInfo&id=$artistid (Returns the artist bio preformatted in html) +getAlbumInfo&id=$albumid (See above, returns album description in html) diff --git a/headphones/api.py b/headphones/api.py index 3da1ed6b..cf452a5b 100644 --- a/headphones/api.py +++ b/headphones/api.py @@ -15,7 +15,7 @@ import headphones -from headphones import db, mb, importer, searcher, postprocessor, versioncheck, logger +from headphones import db, mb, importer, searcher, cache, postprocessor, versioncheck, logger import lib.simplejson as simplejson from xml.dom.minidom import Document @@ -24,7 +24,7 @@ import copy cmd_list = [ 'getIndex', 'getArtist', 'getAlbum', 'getUpcoming', 'getWanted', 'getSimilar', 'getHistory', 'getLogs', 'findArtist', 'findAlbum', 'addArtist', 'delArtist', 'pauseArtist', 'resumeArtist', 'refreshArtist', 'queueAlbum', 'unqueueAlbum', 'forceSearch', 'forceProcess', 'getVersion', 'checkGithub', - 'shutdown', 'restart', 'update', ] + 'shutdown', 'restart', 'update', 'getArtwork', 'getInfo'] class Api(object): @@ -314,3 +314,43 @@ class Api(object): def _update(self, **kwargs): headphones.SIGNAL = 'update' + + def _getArtistArt(self, **kwargs): + + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + self.data = cache.getArtwork(ArtistID=self.id) + + def _getAlbumArt(self, **kwargs): + + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + self.data = cache.getArtwork(AlbumID=self.id) + + def _getArtistInfo(self, **kwargs): + + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + self.data = cache.getInfo(ArtistID=self.id) + + def _getAlbumInfo(self, **kwargs): + + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + self.data = cache.getInfo(AlbumID=self.id) From 40bbdc855f2bebfc7664eb3e37228e24c2a35e20 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 20:37:27 +0530 Subject: [PATCH 27/52] Updated api commands --- headphones/api.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/headphones/api.py b/headphones/api.py index cf452a5b..c90e2734 100644 --- a/headphones/api.py +++ b/headphones/api.py @@ -24,7 +24,7 @@ import copy cmd_list = [ 'getIndex', 'getArtist', 'getAlbum', 'getUpcoming', 'getWanted', 'getSimilar', 'getHistory', 'getLogs', 'findArtist', 'findAlbum', 'addArtist', 'delArtist', 'pauseArtist', 'resumeArtist', 'refreshArtist', 'queueAlbum', 'unqueueAlbum', 'forceSearch', 'forceProcess', 'getVersion', 'checkGithub', - 'shutdown', 'restart', 'update', 'getArtwork', 'getInfo'] + 'shutdown', 'restart', 'update', 'getArtistArt', 'getAlbumArt', 'getArtistInfo', 'getAlbumInfo'] class Api(object): From d34ef512ea091d05c538018a2adc4e8ca806646a Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 20:52:59 +0530 Subject: [PATCH 28/52] Just get the summary rather than the full content for now --- headphones/cache.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/headphones/cache.py b/headphones/cache.py index 2e646c0d..b5544b12 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -183,7 +183,7 @@ class Cache(object): logger.warn('Could not parse data from url: ' + url) return try: - info = data['artist']['bio']['content'] + info = data['artist']['bio']['summary'] except KeyError: logger.debug('No artist bio found on url: ' + url) info = None @@ -220,7 +220,7 @@ class Cache(object): logger.warn('Could not parse data from url: ' + url) return try: - info = data['album']['wiki']['content'] + info = data['album']['wiki']['summary'] except KeyError: logger.debug('No album infomation found from: ' + url) info = None @@ -306,7 +306,7 @@ class Cache(object): if artwork: - # Make sure the info dir exists: + # Make sure the artwork dir exists: if not os.path.isdir(self.path_to_art_cache): try: os.makedirs(self.path_to_art_cache) From 0f862ccad1811d282f111b7153fdbd78c658dc2b Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 21:55:54 +0530 Subject: [PATCH 29/52] Added thumbnails to the caching - called through getThumb(ArtistID/AlbumID) --- API_REFERENCE | 3 ++ headphones/api.py | 22 ++++++++- headphones/cache.py | 110 +++++++++++++++++++++++++++++++++++++++-- headphones/webserve.py | 7 +++ 4 files changed, 137 insertions(+), 5 deletions(-) diff --git a/API_REFERENCE b/API_REFERENCE index 62f28d5d..1798ff23 100644 --- a/API_REFERENCE +++ b/API_REFERENCE @@ -59,3 +59,6 @@ getAlbumArt&id=$albumid (see above) getArtistInfo&id=$artistid (Returns the artist bio preformatted in html) getAlbumInfo&id=$albumid (See above, returns album description in html) + +getArtistThumb&id=$artistid (Returns either a relative path to the cached thumbnail artist image, or an http:// address if the cache dir can't be written to) +getAlbumThumb&id=$albumid (see above) diff --git a/headphones/api.py b/headphones/api.py index c90e2734..b2ea1c18 100644 --- a/headphones/api.py +++ b/headphones/api.py @@ -24,7 +24,7 @@ import copy cmd_list = [ 'getIndex', 'getArtist', 'getAlbum', 'getUpcoming', 'getWanted', 'getSimilar', 'getHistory', 'getLogs', 'findArtist', 'findAlbum', 'addArtist', 'delArtist', 'pauseArtist', 'resumeArtist', 'refreshArtist', 'queueAlbum', 'unqueueAlbum', 'forceSearch', 'forceProcess', 'getVersion', 'checkGithub', - 'shutdown', 'restart', 'update', 'getArtistArt', 'getAlbumArt', 'getArtistInfo', 'getAlbumInfo'] + 'shutdown', 'restart', 'update', 'getArtistArt', 'getAlbumArt', 'getArtistInfo', 'getAlbumInfo', 'getArtistThumb', 'getAlbumThumb'] class Api(object): @@ -354,3 +354,23 @@ class Api(object): self.id = kwargs['id'] self.data = cache.getInfo(AlbumID=self.id) + + def _getArtistThumb(self, **kwargs): + + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + self.data = cache.getThumb(ArtistID=self.id) + + def _getAlbumThumb(self, **kwargs): + + if 'id' not in kwargs: + self.data = 'Missing parameter: id' + return + else: + self.id = kwargs['id'] + + self.data = cache.getThumb(AlbumID=self.id) diff --git a/headphones/cache.py b/headphones/cache.py index b5544b12..bf676d94 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -52,9 +52,13 @@ class Cache(object): info_files = [] artwork_errors = False + artwork_url = None + + thumb_errors = False + thumb_url = None + info_errors = False info = None - artwork_url = None def __init__(self): @@ -63,6 +67,7 @@ class Cache(object): def _exists(self, type): self.artwork_files = glob.glob(os.path.join(self.path_to_art_cache, self.id + '*')) + self.thumb_files = glob.glob(os.path.join(self.path_to_art_cache, 'T_' + self.id + '*')) self.info_files = glob.glob(os.path.join(self.path_to_info_cache, self.id + '*')) if type == 'artwork': @@ -71,6 +76,13 @@ class Cache(object): return True else: return False + + elif type == 'thumb': + + if self.thumb_files: + return True + else: + return False else: @@ -125,6 +137,32 @@ class Cache(object): else: return None + def get_thumb_from_cache(self, ArtistID=None, AlbumID=None): + ''' + Pass a musicbrainz id to this function (either ArtistID or AlbumID) + ''' + + self.query_type = 'thumb' + + if ArtistID: + self.id = ArtistID + self.id_type = 'artist' + else: + self.id = AlbumID + self.id_type = 'album' + + if self._exists('thumb') and self._is_current(self.thumb_files[0]): + return self.thumb_files[0] + else: + self._update_cache() + # If we failed to get artwork, either return the url or the older file + if self.thumb_errors and self.thumb_url: + return self.thumb_url + elif self._exists('thumb'): + return self.thumb_files[0] + else: + return None + def get_info_from_cache(self, ArtistID=None, AlbumID=None): self.query_type = 'info' @@ -192,6 +230,11 @@ class Cache(object): except KeyError: logger.debug('No artist image found on url: ' + url) image_url = None + try: + thumb_url = data['artist']['image'][-3]['#text'] # + except KeyError: + logger.debug('No artist thumbnail image found on url: ' + url) + thumb_url = None else: myDB = db.DBConnection() @@ -229,6 +272,11 @@ class Cache(object): except KeyError: logger.debug('No album image link found on url: ' + url) image_url = None + try: + thumb_url = data['album']['image'][-3]['#text'] + except KeyError: + logger.debug('No album thumbnail image link found on url: ' + url) + thumb_url = None if info: # Make sure the info dir exists: @@ -286,9 +334,8 @@ class Cache(object): f.close() if image_url: - - # If we're just grabbing an info file, no need to open the actual image_url unless it's outdated - if self.query_type == 'info' and self.artwork_files and self._is_current(self.artwork_files[0]): + # If we're just grabbing an info or thumbnail file, no need to open the actual image_url unless it's outdated + if self.query_type != 'artwork' and self.artwork_files and self._is_current(self.artwork_files[0]): return myDB = db.DBConnection() @@ -333,6 +380,48 @@ class Cache(object): logger.error('Unable to write to the cache dir: ' + str(e)) self.artwork_errors = True self.artwork_url = image_url + + if thumb_url: + + # If we're grabbing an artwork or info file, no need to open the actual image_url unless it's outdated + if self.query_type != 'thumb' and self.thumb_files and self._is_current(self.thumb_files[0]): + return + + try: + artwork = urllib2.urlopen(thumb_url).read() + except Exception, e: + logger.error('Unable to open url "' + thumb_url + '". Error: ' + str(e)) + artwork = None + + if artwork: + + # Make sure the artwork dir exists: + if not os.path.isdir(self.path_to_art_cache): + try: + os.makedirs(self.path_to_art_cache) + except Exception, e: + logger.error('Unable to create artwork cache dir. Error: ' + str(e)) + self.thumb_errors = True + self.thumb_url = thumb_url + + #Delete the old stuff + for thumb_file in self.thumb_files: + try: + os.remove(thumb_file) + except: + logger.error('Error deleting file from the cache: ' + thumb_file) + + ext = os.path.splitext(image_url)[1] + + thumb_path = os.path.join(self.path_to_art_cache, 'T_' + self.id + '.' + helpers.today() + ext) + try: + f = open(thumb_path, 'wb') + f.write(artwork) + f.close() + except Exception, e: + logger.error('Unable to write to the cache dir: ' + str(e)) + self.thumb_errors = True + self.thumb_url = image_url def getArtwork(ArtistID=None, AlbumID=None): @@ -346,6 +435,19 @@ def getArtwork(ArtistID=None, AlbumID=None): return artwork_path else: return "cache" + artwork_path[len(headphones.CACHE_DIR):] + +def getThumb(ArtistID=None, AlbumID=None): + + c = Cache() + artwork_path = c.get_thumb_from_cache(ArtistID, AlbumID) + + if not artwork_path: + return None + + if artwork_path.startswith('http://'): + return artwork_path + else: + return "cache" + artwork_path[len(headphones.CACHE_DIR):] def getInfo(ArtistID=None, AlbumID=None): diff --git a/headphones/webserve.py b/headphones/webserve.py index 45d5b3ea..dc138eb1 100644 --- a/headphones/webserve.py +++ b/headphones/webserve.py @@ -605,3 +605,10 @@ class WebInterface(object): return cache.getArtwork(ArtistID, AlbumID) getArtwork.exposed = True + + def getThumb(self, ArtistID=None, AlbumID=None): + + from headphones import cache + return cache.getThumb(ArtistID, AlbumID) + + getThumb.exposed = True From c2b3270eedac1512970da65445826c69f8d33cac Mon Sep 17 00:00:00 2001 From: rembo10 Date: Fri, 22 Jun 2012 22:43:30 +0530 Subject: [PATCH 30/52] A couple of fixes for when we grab different items. Grab info no matter what the query_type, as long as its either outdated or missing. Grab the thumbnail if were grabbing artwork and it's outdated or missing. But only grab the big image if that's specifically what we're looking for - not with any other query types --- headphones/cache.py | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/headphones/cache.py b/headphones/cache.py index bf676d94..86639a95 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -277,8 +277,10 @@ class Cache(object): except KeyError: logger.debug('No album thumbnail image link found on url: ' + url) thumb_url = None - if info: - + + # Save the info no matter what the query type if it's outdated/missing + if info and not (self.info_files and self._is_current(self.info_files[0])): + # Make sure the info dir exists: if not os.path.isdir(self.path_to_info_cache): try: @@ -332,11 +334,9 @@ class Cache(object): else: f = open(new_info_file_path, 'w') f.close() - - if image_url: - # If we're just grabbing an info or thumbnail file, no need to open the actual image_url unless it's outdated - if self.query_type != 'artwork' and self.artwork_files and self._is_current(self.artwork_files[0]): - return + + # Should we grab the artwork here if we're just grabbing thumbs or info?? + if image_url and self.query_type == 'artwork': myDB = db.DBConnection() @@ -381,11 +381,8 @@ class Cache(object): self.artwork_errors = True self.artwork_url = image_url - if thumb_url: - - # If we're grabbing an artwork or info file, no need to open the actual image_url unless it's outdated - if self.query_type != 'thumb' and self.thumb_files and self._is_current(self.thumb_files[0]): - return + # Grab the thumbnail as well if we're getting the full artwork (as long as it's missing/outdated + if thumb_url and self.query_type in ['thumb','artwork'] and not (self.thumb_files and self._is_current(self.thumb_files[0])): try: artwork = urllib2.urlopen(thumb_url).read() From 6f2640f5582361b5656447a21077cb770cda437a Mon Sep 17 00:00:00 2001 From: rembo10 Date: Sat, 23 Jun 2012 12:56:41 +0530 Subject: [PATCH 31/52] Fixed the if/else block when writing info files - before it was writing the info file even if it existed and was current --- headphones/cache.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/headphones/cache.py b/headphones/cache.py index 86639a95..c95882f4 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -309,7 +309,7 @@ class Cache(object): # If there is no info, we should either write an empty file, or make an older file current # just so it doesn't check it every time - else: + elif not info and not (self.info_files and self._is_current(self.info_files[0])): new_info_file_path = os.path.join(self.path_to_info_cache, self.id + '.' + helpers.today() + '.txt') @@ -335,7 +335,7 @@ class Cache(object): f = open(new_info_file_path, 'w') f.close() - # Should we grab the artwork here if we're just grabbing thumbs or info?? + # Should we grab the artwork here if we're just grabbing thumbs or info?? Probably not since the files can be quite big if image_url and self.query_type == 'artwork': myDB = db.DBConnection() From 5eddfbbc30acb0c606559db374b8aa3410c33b05 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Sat, 23 Jun 2012 13:24:26 +0530 Subject: [PATCH 32/52] Added ThumbURLs to the artist & album tables in the DB, modfied API_REFERENCE to reflect --- API_REFERENCE | 2 +- headphones/__init__.py | 14 ++++++++++++-- headphones/cache.py | 7 +++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/API_REFERENCE b/API_REFERENCE index 1798ff23..75e00d95 100644 --- a/API_REFERENCE +++ b/API_REFERENCE @@ -12,7 +12,7 @@ $commands¶meters[&optionalparameters]: getIndex (fetch data from index page. Returns: ArtistName, ArtistSortName, ArtistID, Status, DateAdded, [LatestAlbum, ReleaseDate, AlbumID], HaveTracks, TotalTracks, - IncludeExtras, LastUpdated, ArtworkURL: a remote url to the artwork. To get the cached image path, see getArtistArt command) + IncludeExtras, LastUpdated, [ArtworkURL, ThumbURL]: a remote url to the artwork/thumbnail. To get the cached image path, see getArtistArt command) getArtist&id=$artistid (fetch artist data. returns the artist object (see above) and album info: Status, AlbumASIN, DateAdded, AlbumTitle, ArtistName, ReleaseDate, AlbumID, ArtistID, Type, ArtworkURL: hosted image path. For cached image, see getAlbumArt command) diff --git a/headphones/__init__.py b/headphones/__init__.py index 49548405..ca184949 100644 --- a/headphones/__init__.py +++ b/headphones/__init__.py @@ -672,8 +672,8 @@ def dbcheck(): conn=sqlite3.connect(DB_FILE) c=conn.cursor() - c.execute('CREATE TABLE IF NOT EXISTS artists (ArtistID TEXT UNIQUE, ArtistName TEXT, ArtistSortName TEXT, DateAdded TEXT, Status TEXT, IncludeExtras INTEGER, LatestAlbum TEXT, ReleaseDate TEXT, AlbumID TEXT, HaveTracks INTEGER, TotalTracks INTEGER, LastUpdated TEXT, ArtworkURL 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, Type TEXT, ArtworkURL TEXT)') + c.execute('CREATE TABLE IF NOT EXISTS artists (ArtistID TEXT UNIQUE, ArtistName TEXT, ArtistSortName TEXT, DateAdded TEXT, Status TEXT, IncludeExtras INTEGER, LatestAlbum TEXT, ReleaseDate TEXT, AlbumID TEXT, HaveTracks INTEGER, TotalTracks INTEGER, LastUpdated TEXT, ArtworkURL TEXT, ThumbURL 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, Type TEXT, ArtworkURL TEXT, ThumbURL TEXT)') c.execute('CREATE TABLE IF NOT EXISTS tracks (ArtistID TEXT, ArtistName TEXT, AlbumTitle TEXT, AlbumASIN TEXT, AlbumID TEXT, TrackTitle TEXT, TrackDuration, TrackID TEXT, TrackNumber INTEGER, Location TEXT, BitRate INTEGER, CleanName TEXT, Format TEXT)') c.execute('CREATE TABLE IF NOT EXISTS snatched (AlbumID TEXT, Title TEXT, Size INTEGER, URL TEXT, DateAdded TEXT, Status TEXT, FolderName TEXT)') c.execute('CREATE TABLE IF NOT EXISTS have (ArtistName TEXT, AlbumTitle TEXT, TrackNumber TEXT, TrackTitle TEXT, TrackLength TEXT, BitRate TEXT, Genre TEXT, Date TEXT, TrackID TEXT, Location TEXT, CleanName TEXT, Format TEXT)') @@ -778,6 +778,16 @@ def dbcheck(): c.execute('SELECT ArtworkURL from albums') except sqlite3.OperationalError: c.execute('ALTER TABLE albums ADD COLUMN ArtworkURL TEXT DEFAULT NULL') + + try: + c.execute('SELECT ThumbURL from artists') + except sqlite3.OperationalError: + c.execute('ALTER TABLE artists ADD COLUMN ThumbURL TEXT DEFAULT NULL') + + try: + c.execute('SELECT ThumbURL from albums') + except sqlite3.OperationalError: + c.execute('ALTER TABLE albums ADD COLUMN ThumbURL TEXT DEFAULT NULL') conn.commit() c.close() diff --git a/headphones/cache.py b/headphones/cache.py index c95882f4..5fd9e64d 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -384,6 +384,13 @@ class Cache(object): # Grab the thumbnail as well if we're getting the full artwork (as long as it's missing/outdated if thumb_url and self.query_type in ['thumb','artwork'] and not (self.thumb_files and self._is_current(self.thumb_files[0])): + myDB = db.DBConnection() + + if self.id_type == 'artist': + myDB.action('UPDATE artists SET ThumbURL=? WHERE ArtistID=?', [thumb_url, self.id]) + else: + myDB.action('UPDATE albums SET ThumbURL=? WHERE AlbumID=?', [thumb_url, self.id]) + try: artwork = urllib2.urlopen(thumb_url).read() except Exception, e: From 171faf824c67f836b0ce0b728157f0f8065db0d1 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Sat, 23 Jun 2012 15:25:41 +0530 Subject: [PATCH 33/52] Update the cache (with thumbnails & info only, not large image) when adding an artist/doing an artist update. Add album/artist descriptions to the database as well - removed last.fm getDescriptions function from the importer (replaced with the cache.getThumb), changed the thumbnail size from large to medium (~64px). Updated api_reference --- API_REFERENCE | 4 ++- headphones/__init__.py | 7 ++++- headphones/cache.py | 68 ++++++++++++++++++++++++++++++++++-------- headphones/importer.py | 15 ++++++---- 4 files changed, 75 insertions(+), 19 deletions(-) diff --git a/API_REFERENCE b/API_REFERENCE index 75e00d95..8f19fe1f 100644 --- a/API_REFERENCE +++ b/API_REFERENCE @@ -12,7 +12,9 @@ $commands¶meters[&optionalparameters]: getIndex (fetch data from index page. Returns: ArtistName, ArtistSortName, ArtistID, Status, DateAdded, [LatestAlbum, ReleaseDate, AlbumID], HaveTracks, TotalTracks, - IncludeExtras, LastUpdated, [ArtworkURL, ThumbURL]: a remote url to the artwork/thumbnail. To get the cached image path, see getArtistArt command) + IncludeExtras, LastUpdated, [ArtworkURL, ThumbURL]: a remote url to the artwork/thumbnail. To get the cached image path, see getArtistArt command. + ThumbURL is added/updated when an artist is added/updated. If your using the database method to get the artwork, + it's more reliable to use the ThumbURL than the ArtworkURL) getArtist&id=$artistid (fetch artist data. returns the artist object (see above) and album info: Status, AlbumASIN, DateAdded, AlbumTitle, ArtistName, ReleaseDate, AlbumID, ArtistID, Type, ArtworkURL: hosted image path. For cached image, see getAlbumArt command) diff --git a/headphones/__init__.py b/headphones/__init__.py index ca184949..0e063353 100644 --- a/headphones/__init__.py +++ b/headphones/__init__.py @@ -678,7 +678,7 @@ def dbcheck(): c.execute('CREATE TABLE IF NOT EXISTS snatched (AlbumID TEXT, Title TEXT, Size INTEGER, URL TEXT, DateAdded TEXT, Status TEXT, FolderName TEXT)') c.execute('CREATE TABLE IF NOT EXISTS have (ArtistName TEXT, AlbumTitle TEXT, TrackNumber TEXT, TrackTitle TEXT, TrackLength TEXT, BitRate TEXT, Genre TEXT, Date TEXT, TrackID TEXT, Location TEXT, CleanName TEXT, Format TEXT)') c.execute('CREATE TABLE IF NOT EXISTS lastfmcloud (ArtistName TEXT, ArtistID TEXT, Count INTEGER)') - c.execute('CREATE TABLE IF NOT EXISTS descriptions (ReleaseGroupID TEXT, ReleaseID TEXT, Summary TEXT, Content TEXT)') + c.execute('CREATE TABLE IF NOT EXISTS descriptions (ArtistID TEXT, ReleaseGroupID TEXT, ReleaseID TEXT, Summary TEXT, Content TEXT)') c.execute('CREATE TABLE IF NOT EXISTS releases (ReleaseID TEXT, ReleaseGroupID TEXT, UNIQUE(ReleaseID, ReleaseGroupID))') c.execute('CREATE INDEX IF NOT EXISTS tracks_albumid ON tracks(AlbumID ASC)') c.execute('CREATE INDEX IF NOT EXISTS album_artistid_reldate ON albums(ArtistID ASC, ReleaseDate DESC)') @@ -788,6 +788,11 @@ def dbcheck(): c.execute('SELECT ThumbURL from albums') except sqlite3.OperationalError: c.execute('ALTER TABLE albums ADD COLUMN ThumbURL TEXT DEFAULT NULL') + + try: + c.execute('SELECT ArtistID from descriptions') + except sqlite3.OperationalError: + c.execute('ALTER TABLE descriptions ADD COLUMN ArtistID TEXT DEFAULT NULL') conn.commit() c.close() diff --git a/headphones/cache.py b/headphones/cache.py index 5fd9e64d..6941e66e 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -110,6 +110,22 @@ class Cache(object): return True else: return False + + def _get_thumb_url(self, data): + + thumb_url = None + + try: + images = data[self.id_type]['image'] + except KeyError: + return None + + for image in images: + if image['size'] == 'medium': + thumb_url = image['#text'] + break + + return thumb_url def get_artwork_from_cache(self, ArtistID=None, AlbumID=None): ''' @@ -223,18 +239,22 @@ class Cache(object): try: info = data['artist']['bio']['summary'] except KeyError: - logger.debug('No artist bio found on url: ' + url) + logger.debug('No artist bio summary found on url: ' + url) info = None + try: + info_full = data['artist']['bio']['content'] + except KeyError: + logger.debug('No artist bio found on url: ' + url) + info_full = None try: image_url = data['artist']['image'][-1]['#text'] except KeyError: logger.debug('No artist image found on url: ' + url) image_url = None - try: - thumb_url = data['artist']['image'][-3]['#text'] # - except KeyError: + + thumb_url = self._get_thumb_url(data) + if not thumb_url: logger.debug('No artist thumbnail image found on url: ' + url) - thumb_url = None else: myDB = db.DBConnection() @@ -265,20 +285,35 @@ class Cache(object): try: info = data['album']['wiki']['summary'] except KeyError: - logger.debug('No album infomation found from: ' + url) + logger.debug('No album summary found from: ' + url) info = None + try: + info_full = data['album']['wiki']['content'] + except KeyError: + logger.debug('No album infomation found from: ' + url) + info_full = None try: image_url = data['album']['image'][-1]['#text'] except KeyError: logger.debug('No album image link found on url: ' + url) image_url = None - try: - thumb_url = data['album']['image'][-3]['#text'] - except KeyError: - logger.debug('No album thumbnail image link found on url: ' + url) - thumb_url = None + + thumb_url = self._get_thumb_url(data) + if not thumb_url: + logger.debug('No album thumbnail image found on url: ' + url) + + #Save the content & summary to the database no matter what if we've opened up the url + if info or info_full: + + myDB = db.DBConnection() + + if self.id_type == 'artist': + myDB.action('UPDATE descriptions SET Summary=?, Content=? WHERE ArtistID=?', [info, info_full, self.id]) + else: + myDB.action('UPDATE descriptions SET Summary=?, Content=? WHERE ReleaseGroupID=?', [info, info_full, self.id]) - # Save the info no matter what the query type if it's outdated/missing + # Save the info no matter what the query type if it's outdated/missing (maybe it's redundant to save + # the info files since we're already saving them to the database??? Especially since the DB has summary & content if info and not (self.info_files and self._is_current(self.info_files[0])): # Make sure the info dir exists: @@ -311,6 +346,15 @@ class Cache(object): # just so it doesn't check it every time elif not info and not (self.info_files and self._is_current(self.info_files[0])): + # Make sure the info dir exists: + if not os.path.isdir(self.path_to_info_cache): + try: + os.makedirs(self.path_to_info_cache) + except Exception, e: + logger.error('Unable to create info cache dir. Error: ' + str(e)) + self.info_errors = True + self.info = info + new_info_file_path = os.path.join(self.path_to_info_cache, self.id + '.' + helpers.today() + '.txt') if len(self.info_files) == 1: diff --git a/headphones/importer.py b/headphones/importer.py index 400fc303..fa541970 100644 --- a/headphones/importer.py +++ b/headphones/importer.py @@ -82,6 +82,9 @@ def addArtistIDListToDB(artistidlist): def addArtisttoDB(artistid, extrasonly=False): + # Putting this here to get around the circular import + from headphones import cache + # Can't add various artists - throws an error from MB if artistid == various_artists_mbid: logger.warn('Cannot import Various Artists.') @@ -179,11 +182,6 @@ def addArtisttoDB(artistid, extrasonly=False): newValueDict['Status'] = "Skipped" myDB.upsert("albums", newValueDict, controlValueDict) - - try: - lastfm.getAlbumDescription(rg['id'], artist['artist_name'], rg['title']) - except Exception, e: - logger.error('Attempt to retrieve album description from Last.fm failed: %s' % e) # I changed the albumid from releaseid -> rgid, so might need to delete albums that have a releaseid for release in release_dict['releaselist']: @@ -220,6 +218,9 @@ def addArtisttoDB(artistid, extrasonly=False): myDB.upsert("tracks", newValueDict, controlValueDict) + logger.info(u"Updating album cache for " + rg['title']) + cache.getThumb(AlbumID=rg['id']) + latestalbum = myDB.action('SELECT AlbumTitle, ReleaseDate, AlbumID from albums WHERE ArtistID=? order by ReleaseDate DESC', [artistid]).fetchone() totaltracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID=?', [artistid])) havetracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID=? AND Location IS NOT NULL', [artistid])) + len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ?', [artist['artist_name']])) @@ -241,6 +242,10 @@ def addArtisttoDB(artistid, extrasonly=False): newValueDict['LastUpdated'] = helpers.now() myDB.upsert("artists", newValueDict, controlValueDict) + + logger.info(u"Updating cache for: " + artist['artist_name']) + cache.getThumb(ArtistID=artistid) + logger.info(u"Updating complete for: " + artist['artist_name']) def addReleaseById(rid): From b1ed2da114bd10c1c14638ee6c1deafdc7b23c20 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Sat, 23 Jun 2012 17:46:29 +0530 Subject: [PATCH 34/52] No more caching bios/decriptions to file. Store them in the descriptions db table instead. can be accessed the by getInfo still, which returns a dict with Content and Summary. API updated --- API_REFERENCE | 4 +- headphones/__init__.py | 7 +- headphones/cache.py | 189 ++++++++++++----------------------------- headphones/webserve.py | 6 +- 4 files changed, 69 insertions(+), 137 deletions(-) diff --git a/API_REFERENCE b/API_REFERENCE index 8f19fe1f..c20d32cb 100644 --- a/API_REFERENCE +++ b/API_REFERENCE @@ -59,8 +59,8 @@ update (update headphones - you may want to check the install type in get versio getArtistArt&id=$artistid (Returns either a relative path to the cached image, or a remote url if the image can't be saved to the cache dir) getAlbumArt&id=$albumid (see above) -getArtistInfo&id=$artistid (Returns the artist bio preformatted in html) -getAlbumInfo&id=$albumid (See above, returns album description in html) +getArtistInfo&id=$artistid (Returns Summary and Content, both formatted in html) +getAlbumInfo&id=$albumid (See above, returns Summary and Content) getArtistThumb&id=$artistid (Returns either a relative path to the cached thumbnail artist image, or an http:// address if the cache dir can't be written to) getAlbumThumb&id=$albumid (see above) diff --git a/headphones/__init__.py b/headphones/__init__.py index 0e063353..3ec235d0 100644 --- a/headphones/__init__.py +++ b/headphones/__init__.py @@ -678,7 +678,7 @@ def dbcheck(): c.execute('CREATE TABLE IF NOT EXISTS snatched (AlbumID TEXT, Title TEXT, Size INTEGER, URL TEXT, DateAdded TEXT, Status TEXT, FolderName TEXT)') c.execute('CREATE TABLE IF NOT EXISTS have (ArtistName TEXT, AlbumTitle TEXT, TrackNumber TEXT, TrackTitle TEXT, TrackLength TEXT, BitRate TEXT, Genre TEXT, Date TEXT, TrackID TEXT, Location TEXT, CleanName TEXT, Format TEXT)') c.execute('CREATE TABLE IF NOT EXISTS lastfmcloud (ArtistName TEXT, ArtistID TEXT, Count INTEGER)') - c.execute('CREATE TABLE IF NOT EXISTS descriptions (ArtistID TEXT, ReleaseGroupID TEXT, ReleaseID TEXT, Summary TEXT, Content TEXT)') + c.execute('CREATE TABLE IF NOT EXISTS descriptions (ArtistID TEXT, ReleaseGroupID TEXT, ReleaseID TEXT, Summary TEXT, Content TEXT, LastUpdated TEXT)') c.execute('CREATE TABLE IF NOT EXISTS releases (ReleaseID TEXT, ReleaseGroupID TEXT, UNIQUE(ReleaseID, ReleaseGroupID))') c.execute('CREATE INDEX IF NOT EXISTS tracks_albumid ON tracks(AlbumID ASC)') c.execute('CREATE INDEX IF NOT EXISTS album_artistid_reldate ON albums(ArtistID ASC, ReleaseDate DESC)') @@ -793,6 +793,11 @@ def dbcheck(): c.execute('SELECT ArtistID from descriptions') except sqlite3.OperationalError: c.execute('ALTER TABLE descriptions ADD COLUMN ArtistID TEXT DEFAULT NULL') + + try: + c.execute('SELECT LastUpdated from descriptions') + except sqlite3.OperationalError: + c.execute('ALTER TABLE descriptions ADD COLUMN LastUpdated TEXT DEFAULT NULL') conn.commit() c.close() diff --git a/headphones/cache.py b/headphones/cache.py index 6941e66e..8277d343 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -42,14 +42,13 @@ class Cache(object): """ path_to_art_cache = os.path.join(headphones.CACHE_DIR, 'artwork') - path_to_info_cache = os.path.join(headphones.CACHE_DIR, 'info') id = None id_type = None # 'artist' or 'album' - set automatically depending on whether ArtistID or AlbumID is passed - query_type = None # 'artwork' or 'info' - set automatically + query_type = None # 'artwork','thumb' or 'info' - set automatically artwork_files = [] - info_files = [] + thumb_files = [] artwork_errors = False artwork_url = None @@ -57,8 +56,8 @@ class Cache(object): thumb_errors = False thumb_url = None - info_errors = False - info = None + info_summary = None + info_content = None def __init__(self): @@ -68,7 +67,6 @@ class Cache(object): self.artwork_files = glob.glob(os.path.join(self.path_to_art_cache, self.id + '*')) self.thumb_files = glob.glob(os.path.join(self.path_to_art_cache, 'T_' + self.id + '*')) - self.info_files = glob.glob(os.path.join(self.path_to_info_cache, self.id + '*')) if type == 'artwork': @@ -84,13 +82,6 @@ class Cache(object): else: return False - else: - - if self.info_files: - return True - else: - return False - def _get_age(self, date): # There's probably a better way to do this split_date = date.split('-') @@ -99,10 +90,11 @@ class Cache(object): return days_old - def _is_current(self, file): + def _is_current(self, filename=None, date=None): - base_filename = os.path.basename(file) - date = base_filename.split('.')[1] + if filename: + base_filename = os.path.basename(filename) + date = base_filename.split('.')[1] # Calculate how old the cached file is based on todays date & file date stamp # helpers.today() returns todays date in yyyy-mm-dd format @@ -141,7 +133,7 @@ class Cache(object): self.id = AlbumID self.id_type = 'album' - if self._exists('artwork') and self._is_current(self.artwork_files[0]): + if self._exists('artwork') and self._is_current(filename=self.artwork_files[0]): return self.artwork_files[0] else: self._update_cache() @@ -167,7 +159,7 @@ class Cache(object): self.id = AlbumID self.id_type = 'album' - if self._exists('thumb') and self._is_current(self.thumb_files[0]): + if self._exists('thumb') and self._is_current(filename=self.thumb_files[0]): return self.thumb_files[0] else: self._update_cache() @@ -182,34 +174,32 @@ class Cache(object): def get_info_from_cache(self, ArtistID=None, AlbumID=None): self.query_type = 'info' + myDB = db.DBConnection() if ArtistID: self.id = ArtistID self.id_type = 'artist' + db_info = myDB.action('SELECT Summary, Content, LastUpdated FROM descriptions WHERE ArtistID=?', [self.id]).fetchone() else: self.id = AlbumID self.id_type = 'album' - - if self._exists('info') and self._is_current(self.info_files[0]): - f = open(self.info_files[0], 'r').read() - return f.decode('utf-8') - else: - self._update_cache() - - if self.info_errors and self.info: - return self.info - - elif self._exists('info'): - f = open(self.info_files[0],'r').read() - return f.decode('utf-8') - - else: - return None + db_info = myDB.action('SELECT Summary, Content, LastUpdated FROM descriptions WHERE ReleaseGroupID=?', [self.id]).fetchone() + if not db_info or not db_info['LastUpdated'] or not self._is_current(date=db_info['LastUpdated']): + + self._update_cache() + info_dict = { 'Summary' : self.info_summary, 'Content' : self.info_content } + return info_dict + + else: + info_dict = { 'Summary' : db_info['Summary'], 'Content' : db_info['Content'] } + return info_dict + def _update_cache(self): ''' Since we call the same url for both info and artwork, we'll update both at the same time ''' + myDB = db.DBConnection() # Since lastfm uses release ids rather than release group ids for albums, we have to do a artist + album search for albums if self.id_type == 'artist': @@ -229,7 +219,7 @@ class Cache(object): logger.warn('Could not open url: ' + url) return - if result: + if result: try: data = simplejson.JSONDecoder().decode(result) @@ -237,15 +227,15 @@ class Cache(object): logger.warn('Could not parse data from url: ' + url) return try: - info = data['artist']['bio']['summary'] + self.info_summary = data['artist']['bio']['summary'] except KeyError: logger.debug('No artist bio summary found on url: ' + url) - info = None + self.info_summary = None try: - info_full = data['artist']['bio']['content'] + self.info_content = data['artist']['bio']['content'] except KeyError: logger.debug('No artist bio found on url: ' + url) - info_full = None + self.info_content = None try: image_url = data['artist']['image'][-1]['#text'] except KeyError: @@ -257,7 +247,7 @@ class Cache(object): logger.debug('No artist thumbnail image found on url: ' + url) else: - myDB = db.DBConnection() + dbartist = myDB.action('SELECT ArtistName, AlbumTitle FROM albums WHERE AlbumID=?', [self.id]).fetchone() params = { "method": "album.getInfo", @@ -283,15 +273,15 @@ class Cache(object): logger.warn('Could not parse data from url: ' + url) return try: - info = data['album']['wiki']['summary'] + self.info_summary = data['album']['wiki']['summary'] except KeyError: logger.debug('No album summary found from: ' + url) - info = None + self.info_summary = None try: - info_full = data['album']['wiki']['content'] + self.info_content = data['album']['wiki']['content'] except KeyError: logger.debug('No album infomation found from: ' + url) - info_full = None + self.info_content = None try: image_url = data['album']['image'][-1]['#text'] except KeyError: @@ -303,91 +293,33 @@ class Cache(object): logger.debug('No album thumbnail image found on url: ' + url) #Save the content & summary to the database no matter what if we've opened up the url - if info or info_full: - - myDB = db.DBConnection() - - if self.id_type == 'artist': - myDB.action('UPDATE descriptions SET Summary=?, Content=? WHERE ArtistID=?', [info, info_full, self.id]) - else: - myDB.action('UPDATE descriptions SET Summary=?, Content=? WHERE ReleaseGroupID=?', [info, info_full, self.id]) - - # Save the info no matter what the query type if it's outdated/missing (maybe it's redundant to save - # the info files since we're already saving them to the database??? Especially since the DB has summary & content - if info and not (self.info_files and self._is_current(self.info_files[0])): + if self.id_type == 'artist': + controlValueDict = {"ArtistID": self.id} + else: + controlValueDict = {"ReleaseGroupID": self.id} - # Make sure the info dir exists: - if not os.path.isdir(self.path_to_info_cache): - try: - os.makedirs(self.path_to_info_cache) - except Exception, e: - logger.error('Unable to create info cache dir. Error: ' + str(e)) - self.info_errors = True - self.info = info - - # Delete any old files and replace it with a new one - for info_file in self.info_files: - try: - os.remove(info_file) - except: - logger.error('Error deleting file from the cache: ' + info_file) - - info_file_path = os.path.join(self.path_to_info_cache, self.id + '.' + helpers.today() + '.txt') - try: - f = open(info_file_path, 'w') - f.write(info.encode('utf-8')) - f.close() - except Exception, e: - logger.error('Unable to write to the cache dir: ' + str(e)) - self.info_errors = True - self.info = info - - # If there is no info, we should either write an empty file, or make an older file current - # just so it doesn't check it every time - elif not info and not (self.info_files and self._is_current(self.info_files[0])): - - # Make sure the info dir exists: - if not os.path.isdir(self.path_to_info_cache): - try: - os.makedirs(self.path_to_info_cache) - except Exception, e: - logger.error('Unable to create info cache dir. Error: ' + str(e)) - self.info_errors = True - self.info = info - - new_info_file_path = os.path.join(self.path_to_info_cache, self.id + '.' + helpers.today() + '.txt') - - if len(self.info_files) == 1: - try: - os.rename(self.info_files[0], new_info_file_path) - except Exception, e: - logger.warn('Error renaming cached info file: ' + str(e)) - - elif len(self.info_files) > 1: - for info_file in self.info_files[1:]: - try: - os.remove(info_file) - except Exception, e: - logger.warn('Error removing cached info file "' + info_file + '". Error: ' + str(e)) + newValueDict = {"Summary": self.info_summary, + "Content": self.info_content, + "LastUpdated": helpers.today()} - try: - os.rename(self.info_files[0], new_info_file_path) - except Exception, e: - logger.warn('Error renaming cached info file: ' + str(e)) - - else: - f = open(new_info_file_path, 'w') - f.close() - - # Should we grab the artwork here if we're just grabbing thumbs or info?? Probably not since the files can be quite big - if image_url and self.query_type == 'artwork': - - myDB = db.DBConnection() + myDB.upsert("descriptions", newValueDict, controlValueDict) + # Save the image URL to the database + if image_url: if self.id_type == 'artist': myDB.action('UPDATE artists SET ArtworkURL=? WHERE ArtistID=?', [image_url, self.id]) else: myDB.action('UPDATE albums SET ArtworkURL=? WHERE AlbumID=?', [image_url, self.id]) + + # Save the thumb URL to the database + if thumb_url: + if self.id_type == 'artist': + myDB.action('UPDATE artists SET ThumbURL=? WHERE ArtistID=?', [thumb_url, self.id]) + else: + myDB.action('UPDATE albums SET ThumbURL=? WHERE AlbumID=?', [thumb_url, self.id]) + + # Should we grab the artwork here if we're just grabbing thumbs or info?? Probably not since the files can be quite big + if image_url and self.query_type == 'artwork': try: artwork = urllib2.urlopen(image_url).read() @@ -428,13 +360,6 @@ class Cache(object): # Grab the thumbnail as well if we're getting the full artwork (as long as it's missing/outdated if thumb_url and self.query_type in ['thumb','artwork'] and not (self.thumb_files and self._is_current(self.thumb_files[0])): - myDB = db.DBConnection() - - if self.id_type == 'artist': - myDB.action('UPDATE artists SET ThumbURL=? WHERE ArtistID=?', [thumb_url, self.id]) - else: - myDB.action('UPDATE albums SET ThumbURL=? WHERE AlbumID=?', [thumb_url, self.id]) - try: artwork = urllib2.urlopen(thumb_url).read() except Exception, e: @@ -500,9 +425,7 @@ def getThumb(ArtistID=None, AlbumID=None): def getInfo(ArtistID=None, AlbumID=None): c = Cache() - info = c.get_info_from_cache(ArtistID, AlbumID) - if not info: - return None + info_dict = c.get_info_from_cache(ArtistID, AlbumID) - return info + return info_dict diff --git a/headphones/webserve.py b/headphones/webserve.py index dc138eb1..4fabb3fd 100644 --- a/headphones/webserve.py +++ b/headphones/webserve.py @@ -28,6 +28,8 @@ import headphones from headphones import logger, searcher, db, importer, mb, lastfm, librarysync from headphones.helpers import checked, radio +import lib.simplejson as simplejson + def serve_template(templatename, **kwargs): @@ -595,7 +597,9 @@ class WebInterface(object): def getInfo(self, ArtistID=None, AlbumID=None): from headphones import cache - return cache.getInfo(ArtistID, AlbumID) + info_dict = cache.getInfo(ArtistID, AlbumID) + + return simplejson.dumps(info_dict) getInfo.exposed = True From 7e9a1d11c20f67d08818538bbe917d319e8e4fcf Mon Sep 17 00:00:00 2001 From: rembo10 Date: Sun, 24 Jun 2012 18:20:04 +0530 Subject: [PATCH 35/52] Put some timeouts on the urlopens --- headphones/cache.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/headphones/cache.py b/headphones/cache.py index 8277d343..fa3e1083 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -214,7 +214,7 @@ class Cache(object): logger.debug('Retrieving artist information from: ' + url) try: - result = urllib2.urlopen(url).read() + result = urllib2.urlopen(url, timeout=20).read() except: logger.warn('Could not open url: ' + url) return @@ -261,7 +261,7 @@ class Cache(object): logger.debug('Retrieving artist information from: ' + url) try: - result = urllib2.urlopen(url).read() + result = urllib2.urlopen(url, timeout=20).read() except: logger.warn('Could not open url: ' + url) return @@ -322,7 +322,7 @@ class Cache(object): if image_url and self.query_type == 'artwork': try: - artwork = urllib2.urlopen(image_url).read() + artwork = urllib2.urlopen(image_url, timeout=20).read() except Exception, e: logger.error('Unable to open url "' + image_url + '". Error: ' + str(e)) artwork = None @@ -361,7 +361,7 @@ class Cache(object): if thumb_url and self.query_type in ['thumb','artwork'] and not (self.thumb_files and self._is_current(self.thumb_files[0])): try: - artwork = urllib2.urlopen(thumb_url).read() + artwork = urllib2.urlopen(thumb_url, timeout=20).read() except Exception, e: logger.error('Unable to open url "' + thumb_url + '". Error: ' + str(e)) artwork = None From 52dd47db4c3016812941daa3c1d7311f77a59494 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Mon, 25 Jun 2012 15:16:09 +0530 Subject: [PATCH 36/52] Moved jquery libs to the main js/lib folder --- data/js/libs/jquery-1.7.2.min.js | 4 + data/js/libs/jquery-ui.min.js | 121 +++++++++++++++++++++++++++++++ 2 files changed, 125 insertions(+) create mode 100644 data/js/libs/jquery-1.7.2.min.js create mode 100644 data/js/libs/jquery-ui.min.js diff --git a/data/js/libs/jquery-1.7.2.min.js b/data/js/libs/jquery-1.7.2.min.js new file mode 100644 index 00000000..16ad06c5 --- /dev/null +++ b/data/js/libs/jquery-1.7.2.min.js @@ -0,0 +1,4 @@ +/*! jQuery v1.7.2 jquery.com | jquery.org/license */ +(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"":"")+""),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){if(c!=="border")for(;e=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
a",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="
"+""+"
",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="
t
",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="
",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function( +a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;le&&j.push({elem:this,matches:d.slice(e)});for(k=0;k0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return bc[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="

";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h0)for(h=g;h=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*",""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div
","
"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f +.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1>");try{for(;d1&&l0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]===""&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("
").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); \ No newline at end of file diff --git a/data/js/libs/jquery-ui.min.js b/data/js/libs/jquery-ui.min.js new file mode 100644 index 00000000..886976df --- /dev/null +++ b/data/js/libs/jquery-ui.min.js @@ -0,0 +1,121 @@ +/*! jQuery UI - v1.8.19 - 2012-04-16 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.core.js +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ +(function(a,b){function c(b,c){var e=b.nodeName.toLowerCase();if("area"===e){var f=b.parentNode,g=f.name,h;return!b.href||!g||f.nodeName.toLowerCase()!=="map"?!1:(h=a("img[usemap=#"+g+"]")[0],!!h&&d(h))}return(/input|select|textarea|button|object/.test(e)?!b.disabled:"a"==e?b.href||c:c)&&d(b)}function d(b){return!a(b).parents().andSelf().filter(function(){return a.curCSS(this,"visibility")==="hidden"||a.expr.filters.hidden(this)}).length}a.ui=a.ui||{};if(a.ui.version)return;a.extend(a.ui,{version:"1.8.19",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}}),a.fn.extend({propAttr:a.fn.prop||a.fn.attr,_focus:a.fn.focus,focus:function(b,c){return typeof b=="number"?this.each(function(){var d=this;setTimeout(function(){a(d).focus(),c&&c.call(d)},b)}):this._focus.apply(this,arguments)},scrollParent:function(){var b;return a.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?b=this.parents().filter(function(){return/(relative|absolute|fixed)/.test(a.curCSS(this,"position",1))&&/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0):b=this.parents().filter(function(){return/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0),/fixed/.test(this.css("position"))||!b.length?a(document):b},zIndex:function(c){if(c!==b)return this.css("zIndex",c);if(this.length){var d=a(this[0]),e,f;while(d.length&&d[0]!==document){e=d.css("position");if(e==="absolute"||e==="relative"||e==="fixed"){f=parseInt(d.css("zIndex"),10);if(!isNaN(f)&&f!==0)return f}d=d.parent()}}return 0},disableSelection:function(){return this.bind((a.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),a.each(["Width","Height"],function(c,d){function h(b,c,d,f){return a.each(e,function(){c-=parseFloat(a.curCSS(b,"padding"+this,!0))||0,d&&(c-=parseFloat(a.curCSS(b,"border"+this+"Width",!0))||0),f&&(c-=parseFloat(a.curCSS(b,"margin"+this,!0))||0)}),c}var e=d==="Width"?["Left","Right"]:["Top","Bottom"],f=d.toLowerCase(),g={innerWidth:a.fn.innerWidth,innerHeight:a.fn.innerHeight,outerWidth:a.fn.outerWidth,outerHeight:a.fn.outerHeight};a.fn["inner"+d]=function(c){return c===b?g["inner"+d].call(this):this.each(function(){a(this).css(f,h(this,c)+"px")})},a.fn["outer"+d]=function(b,c){return typeof b!="number"?g["outer"+d].call(this,b):this.each(function(){a(this).css(f,h(this,b,!0,c)+"px")})}}),a.extend(a.expr[":"],{data:function(b,c,d){return!!a.data(b,d[3])},focusable:function(b){return c(b,!isNaN(a.attr(b,"tabindex")))},tabbable:function(b){var d=a.attr(b,"tabindex"),e=isNaN(d);return(e||d>=0)&&c(b,!e)}}),a(function(){var b=document.body,c=b.appendChild(c=document.createElement("div"));c.offsetHeight,a.extend(c.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0}),a.support.minHeight=c.offsetHeight===100,a.support.selectstart="onselectstart"in c,b.removeChild(c).style.display="none"}),a.extend(a.ui,{plugin:{add:function(b,c,d){var e=a.ui[b].prototype;for(var f in d)e.plugins[f]=e.plugins[f]||[],e.plugins[f].push([c,d[f]])},call:function(a,b,c){var d=a.plugins[b];if(!d||!a.element[0].parentNode)return;for(var e=0;e0?!0:(b[d]=1,e=b[d]>0,b[d]=0,e)},isOverAxis:function(a,b,c){return a>b&&a=9||!!b.button?this._mouseStarted?(this._mouseDrag(b),b.preventDefault()):(this._mouseDistanceMet(b)&&this._mouseDelayMet(b)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,b)!==!1,this._mouseStarted?this._mouseDrag(b):this._mouseUp(b)),!this._mouseStarted):this._mouseUp(b)},_mouseUp:function(b){return a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,b.target==this._mouseDownEvent.target&&a.data(b.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(b)),!1},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(a){return this.mouseDelayMet},_mouseStart:function(a){},_mouseDrag:function(a){},_mouseStop:function(a){},_mouseCapture:function(a){return!0}})})(jQuery);/*! jQuery UI - v1.8.19 - 2012-04-16 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.position.js +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ +(function(a,b){a.ui=a.ui||{};var c=/left|center|right/,d=/top|center|bottom/,e="center",f={},g=a.fn.position,h=a.fn.offset;a.fn.position=function(b){if(!b||!b.of)return g.apply(this,arguments);b=a.extend({},b);var h=a(b.of),i=h[0],j=(b.collision||"flip").split(" "),k=b.offset?b.offset.split(" "):[0,0],l,m,n;return i.nodeType===9?(l=h.width(),m=h.height(),n={top:0,left:0}):i.setTimeout?(l=h.width(),m=h.height(),n={top:h.scrollTop(),left:h.scrollLeft()}):i.preventDefault?(b.at="left top",l=m=0,n={top:b.of.pageY,left:b.of.pageX}):(l=h.outerWidth(),m=h.outerHeight(),n=h.offset()),a.each(["my","at"],function(){var a=(b[this]||"").split(" ");a.length===1&&(a=c.test(a[0])?a.concat([e]):d.test(a[0])?[e].concat(a):[e,e]),a[0]=c.test(a[0])?a[0]:e,a[1]=d.test(a[1])?a[1]:e,b[this]=a}),j.length===1&&(j[1]=j[0]),k[0]=parseInt(k[0],10)||0,k.length===1&&(k[1]=k[0]),k[1]=parseInt(k[1],10)||0,b.at[0]==="right"?n.left+=l:b.at[0]===e&&(n.left+=l/2),b.at[1]==="bottom"?n.top+=m:b.at[1]===e&&(n.top+=m/2),n.left+=k[0],n.top+=k[1],this.each(function(){var c=a(this),d=c.outerWidth(),g=c.outerHeight(),h=parseInt(a.curCSS(this,"marginLeft",!0))||0,i=parseInt(a.curCSS(this,"marginTop",!0))||0,o=d+h+(parseInt(a.curCSS(this,"marginRight",!0))||0),p=g+i+(parseInt(a.curCSS(this,"marginBottom",!0))||0),q=a.extend({},n),r;b.my[0]==="right"?q.left-=d:b.my[0]===e&&(q.left-=d/2),b.my[1]==="bottom"?q.top-=g:b.my[1]===e&&(q.top-=g/2),f.fractions||(q.left=Math.round(q.left),q.top=Math.round(q.top)),r={left:q.left-h,top:q.top-i},a.each(["left","top"],function(c,e){a.ui.position[j[c]]&&a.ui.position[j[c]][e](q,{targetWidth:l,targetHeight:m,elemWidth:d,elemHeight:g,collisionPosition:r,collisionWidth:o,collisionHeight:p,offset:k,my:b.my,at:b.at})}),a.fn.bgiframe&&c.bgiframe(),c.offset(a.extend(q,{using:b.using}))})},a.ui.position={fit:{left:function(b,c){var d=a(window),e=c.collisionPosition.left+c.collisionWidth-d.width()-d.scrollLeft();b.left=e>0?b.left-e:Math.max(b.left-c.collisionPosition.left,b.left)},top:function(b,c){var d=a(window),e=c.collisionPosition.top+c.collisionHeight-d.height()-d.scrollTop();b.top=e>0?b.top-e:Math.max(b.top-c.collisionPosition.top,b.top)}},flip:{left:function(b,c){if(c.at[0]===e)return;var d=a(window),f=c.collisionPosition.left+c.collisionWidth-d.width()-d.scrollLeft(),g=c.my[0]==="left"?-c.elemWidth:c.my[0]==="right"?c.elemWidth:0,h=c.at[0]==="left"?c.targetWidth:-c.targetWidth,i=-2*c.offset[0];b.left+=c.collisionPosition.left<0?g+h+i:f>0?g+h+i:0},top:function(b,c){if(c.at[1]===e)return;var d=a(window),f=c.collisionPosition.top+c.collisionHeight-d.height()-d.scrollTop(),g=c.my[1]==="top"?-c.elemHeight:c.my[1]==="bottom"?c.elemHeight:0,h=c.at[1]==="top"?c.targetHeight:-c.targetHeight,i=-2*c.offset[1];b.top+=c.collisionPosition.top<0?g+h+i:f>0?g+h+i:0}}},a.offset.setOffset||(a.offset.setOffset=function(b,c){/static/.test(a.curCSS(b,"position"))&&(b.style.position="relative");var d=a(b),e=d.offset(),f=parseInt(a.curCSS(b,"top",!0),10)||0,g=parseInt(a.curCSS(b,"left",!0),10)||0,h={top:c.top-e.top+f,left:c.left-e.left+g};"using"in c?c.using.call(b,h):d.css(h)},a.fn.offset=function(b){var c=this[0];return!c||!c.ownerDocument?null:b?this.each(function(){a.offset.setOffset(this,b)}):h.call(this)}),function(){var b=document.getElementsByTagName("body")[0],c=document.createElement("div"),d,e,g,h,i;d=document.createElement(b?"div":"body"),g={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},b&&a.extend(g,{position:"absolute",left:"-1000px",top:"-1000px"});for(var j in g)d.style[j]=g[j];d.appendChild(c),e=b||document.documentElement,e.insertBefore(d,e.firstChild),c.style.cssText="position: absolute; left: 10.7432222px; top: 10.432325px; height: 30px; width: 201px;",h=a(c).offset(function(a,b){return b}).offset(),d.innerHTML="",e.removeChild(d),i=h.top+h.left+(b?2e3:0),f.fractions=i>21&&i<22}()})(jQuery);/*! jQuery UI - v1.8.19 - 2012-04-16 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.draggable.js +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ +(function(a,b){a.widget("ui.draggable",a.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1},_create:function(){this.options.helper=="original"&&!/^(?:r|a|f)/.test(this.element.css("position"))&&(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},destroy:function(){if(!this.element.data("draggable"))return;return this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy(),this},_mouseCapture:function(b){var c=this.options;return this.helper||c.disabled||a(b.target).is(".ui-resizable-handle")?!1:(this.handle=this._getHandle(b),this.handle?(c.iframeFix&&a(c.iframeFix===!0?"iframe":c.iframeFix).each(function(){a('
').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(a(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(b){var c=this.options;return this.helper=this._createHelper(b),this._cacheHelperProportions(),a.ui.ddmanager&&(a.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(b),this.originalPageX=b.pageX,this.originalPageY=b.pageY,c.cursorAt&&this._adjustOffsetFromHelper(c.cursorAt),c.containment&&this._setContainment(),this._trigger("start",b)===!1?(this._clear(),!1):(this._cacheHelperProportions(),a.ui.ddmanager&&!c.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b),this.helper.addClass("ui-draggable-dragging"),this._mouseDrag(b,!0),a.ui.ddmanager&&a.ui.ddmanager.dragStart(this,b),!0)},_mouseDrag:function(b,c){this.position=this._generatePosition(b),this.positionAbs=this._convertPositionTo("absolute");if(!c){var d=this._uiHash();if(this._trigger("drag",b,d)===!1)return this._mouseUp({}),!1;this.position=d.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";return a.ui.ddmanager&&a.ui.ddmanager.drag(this,b),!1},_mouseStop:function(b){var c=!1;a.ui.ddmanager&&!this.options.dropBehaviour&&(c=a.ui.ddmanager.drop(this,b)),this.dropped&&(c=this.dropped,this.dropped=!1);if((!this.element[0]||!this.element[0].parentNode)&&this.options.helper=="original")return!1;if(this.options.revert=="invalid"&&!c||this.options.revert=="valid"&&c||this.options.revert===!0||a.isFunction(this.options.revert)&&this.options.revert.call(this.element,c)){var d=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){d._trigger("stop",b)!==!1&&d._clear()})}else this._trigger("stop",b)!==!1&&this._clear();return!1},_mouseUp:function(b){return this.options.iframeFix===!0&&a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),a.ui.ddmanager&&a.ui.ddmanager.dragStop(this,b),a.ui.mouse.prototype._mouseUp.call(this,b)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(b){var c=!this.options.handle||!a(this.options.handle,this.element).length?!0:!1;return a(this.options.handle,this.element).find("*").andSelf().each(function(){this==b.target&&(c=!0)}),c},_createHelper:function(b){var c=this.options,d=a.isFunction(c.helper)?a(c.helper.apply(this.element[0],[b])):c.helper=="clone"?this.element.clone().removeAttr("id"):this.element;return d.parents("body").length||d.appendTo(c.appendTo=="parent"?this.element[0].parentNode:c.appendTo),d[0]!=this.element[0]&&!/(fixed|absolute)/.test(d.css("position"))&&d.css("position","absolute"),d},_adjustOffsetFromHelper:function(b){typeof b=="string"&&(b=b.split(" ")),a.isArray(b)&&(b={left:+b[0],top:+b[1]||0}),"left"in b&&(this.offset.click.left=b.left+this.margins.left),"right"in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left),"top"in b&&(this.offset.click.top=b.top+this.margins.top),"bottom"in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(b.left+=this.scrollParent.scrollLeft(),b.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)b={top:0,left:0};return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.element.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var b=this.options;b.containment=="parent"&&(b.containment=this.helper[0].parentNode);if(b.containment=="document"||b.containment=="window")this.containment=[b.containment=="document"?0:a(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,b.containment=="document"?0:a(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(b.containment=="document"?0:a(window).scrollLeft())+a(b.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(b.containment=="document"?0:a(window).scrollTop())+(a(b.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(b.containment)&&b.containment.constructor!=Array){var c=a(b.containment),d=c[0];if(!d)return;var e=c.offset(),f=a(d).css("overflow")!="hidden";this.containment=[(parseInt(a(d).css("borderLeftWidth"),10)||0)+(parseInt(a(d).css("paddingLeft"),10)||0),(parseInt(a(d).css("borderTopWidth"),10)||0)+(parseInt(a(d).css("paddingTop"),10)||0),(f?Math.max(d.scrollWidth,d.offsetWidth):d.offsetWidth)-(parseInt(a(d).css("borderLeftWidth"),10)||0)-(parseInt(a(d).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(f?Math.max(d.scrollHeight,d.offsetHeight):d.offsetHeight)-(parseInt(a(d).css("borderTopWidth"),10)||0)-(parseInt(a(d).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=c}else b.containment.constructor==Array&&(this.containment=b.containment)},_convertPositionTo:function(b,c){c||(c=this.position);var d=b=="absolute"?1:-1,e=this.options,f=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=/(html|body)/i.test(f[0].tagName);return{top:c.top+this.offset.relative.top*d+this.offset.parent.top*d-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():g?0:f.scrollTop())*d),left:c.left+this.offset.relative.left*d+this.offset.parent.left*d-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:f.scrollLeft())*d)}},_generatePosition:function(b){var c=this.options,d=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(d[0].tagName),f=b.pageX,g=b.pageY;if(this.originalPosition){var h;if(this.containment){if(this.relative_container){var i=this.relative_container.offset();h=[this.containment[0]+i.left,this.containment[1]+i.top,this.containment[2]+i.left,this.containment[3]+i.top]}else h=this.containment;b.pageX-this.offset.click.lefth[2]&&(f=h[2]+this.offset.click.left),b.pageY-this.offset.click.top>h[3]&&(g=h[3]+this.offset.click.top)}if(c.grid){var j=c.grid[1]?this.originalPageY+Math.round((g-this.originalPageY)/c.grid[1])*c.grid[1]:this.originalPageY;g=h?j-this.offset.click.toph[3]?j-this.offset.click.toph[2]?k-this.offset.click.left=0;k--){var l=d.snapElements[k].left,m=l+d.snapElements[k].width,n=d.snapElements[k].top,o=n+d.snapElements[k].height;if(!(l-f=k&&g<=l||h>=k&&h<=l||gl)&&(e>=i&&e<=j||f>=i&&f<=j||ej);default:return!1}},a.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(b,c){var d=a.ui.ddmanager.droppables[b.options.scope]||[],e=c?c.type:null,f=(b.currentItem||b.element).find(":data(droppable)").andSelf();g:for(var h=0;h
').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("resizable",this.element.data("resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=c.handles||(a(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se");if(this.handles.constructor==String){this.handles=="all"&&(this.handles="n,e,s,w,se,sw,ne,nw");var d=this.handles.split(",");this.handles={};for(var e=0;e');/sw|se|ne|nw/.test(f)&&h.css({zIndex:++c.zIndex}),"se"==f&&h.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[f]=".ui-resizable-"+f,this.element.append(h)}}this._renderAxis=function(b){b=b||this.element;for(var c in this.handles){this.handles[c].constructor==String&&(this.handles[c]=a(this.handles[c],this.element).show());if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var d=a(this.handles[c],this.element),e=0;e=/sw|ne|nw|se|n|s/.test(c)?d.outerHeight():d.outerWidth();var f=["padding",/ne|nw|n/.test(c)?"Top":/se|sw|s/.test(c)?"Bottom":/^e$/.test(c)?"Right":"Left"].join("");b.css(f,e),this._proportionallyResize()}if(!a(this.handles[c]).length)continue}},this._renderAxis(this.element),this._handles=a(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){if(!b.resizing){if(this.className)var a=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);b.axis=a&&a[1]?a[1]:"se"}}),c.autoHide&&(this._handles.hide(),a(this.element).addClass("ui-resizable-autohide").hover(function(){if(c.disabled)return;a(this).removeClass("ui-resizable-autohide"),b._handles.show()},function(){if(c.disabled)return;b.resizing||(a(this).addClass("ui-resizable-autohide"),b._handles.hide())})),this._mouseInit()},destroy:function(){this._mouseDestroy();var b=function(b){a(b).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){b(this.element);var c=this.element;c.after(this.originalElement.css({position:c.css("position"),width:c.outerWidth(),height:c.outerHeight(),top:c.css("top"),left:c.css("left")})).remove()}return this.originalElement.css("resize",this.originalResizeStyle),b(this.originalElement),this},_mouseCapture:function(b){var c=!1;for(var d in this.handles)a(this.handles[d])[0]==b.target&&(c=!0);return!this.options.disabled&&c},_mouseStart:function(b){var d=this.options,e=this.element.position(),f=this.element;this.resizing=!0,this.documentScroll={top:a(document).scrollTop(),left:a(document).scrollLeft()},(f.is(".ui-draggable")||/absolute/.test(f.css("position")))&&f.css({position:"absolute",top:e.top,left:e.left}),this._renderProxy();var g=c(this.helper.css("left")),h=c(this.helper.css("top"));d.containment&&(g+=a(d.containment).scrollLeft()||0,h+=a(d.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:g,top:h},this.size=this._helper?{width:f.outerWidth(),height:f.outerHeight()}:{width:f.width(),height:f.height()},this.originalSize=this._helper?{width:f.outerWidth(),height:f.outerHeight()}:{width:f.width(),height:f.height()},this.originalPosition={left:g,top:h},this.sizeDiff={width:f.outerWidth()-f.width(),height:f.outerHeight()-f.height()},this.originalMousePosition={left:b.pageX,top:b.pageY},this.aspectRatio=typeof d.aspectRatio=="number"?d.aspectRatio:this.originalSize.width/this.originalSize.height||1;var i=a(".ui-resizable-"+this.axis).css("cursor");return a("body").css("cursor",i=="auto"?this.axis+"-resize":i),f.addClass("ui-resizable-resizing"),this._propagate("start",b),!0},_mouseDrag:function(b){var c=this.helper,d=this.options,e={},f=this,g=this.originalMousePosition,h=this.axis,i=b.pageX-g.left||0,j=b.pageY-g.top||0,k=this._change[h];if(!k)return!1;var l=k.apply(this,[b,i,j]),m=a.browser.msie&&a.browser.version<7,n=this.sizeDiff;this._updateVirtualBoundaries(b.shiftKey);if(this._aspectRatio||b.shiftKey)l=this._updateRatio(l,b);return l=this._respectSize(l,b),this._propagate("resize",b),c.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"}),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),this._updateCache(l),this._trigger("resize",b,this.ui()),!1},_mouseStop:function(b){this.resizing=!1;var c=this.options,d=this;if(this._helper){var e=this._proportionallyResizeElements,f=e.length&&/textarea/i.test(e[0].nodeName),g=f&&a.ui.hasScroll(e[0],"left")?0:d.sizeDiff.height,h=f?0:d.sizeDiff.width,i={width:d.helper.width()-h,height:d.helper.height()-g},j=parseInt(d.element.css("left"),10)+(d.position.left-d.originalPosition.left)||null,k=parseInt(d.element.css("top"),10)+(d.position.top-d.originalPosition.top)||null;c.animate||this.element.css(a.extend(i,{top:k,left:j})),d.helper.height(d.size.height),d.helper.width(d.size.width),this._helper&&!c.animate&&this._proportionallyResize()}return a("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",b),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(a){var b=this.options,c,e,f,g,h;h={minWidth:d(b.minWidth)?b.minWidth:0,maxWidth:d(b.maxWidth)?b.maxWidth:Infinity,minHeight:d(b.minHeight)?b.minHeight:0,maxHeight:d(b.maxHeight)?b.maxHeight:Infinity};if(this._aspectRatio||a)c=h.minHeight*this.aspectRatio,f=h.minWidth/this.aspectRatio,e=h.maxHeight*this.aspectRatio,g=h.maxWidth/this.aspectRatio,c>h.minWidth&&(h.minWidth=c),f>h.minHeight&&(h.minHeight=f),ea.width,k=d(a.height)&&e.minHeight&&e.minHeight>a.height;j&&(a.width=e.minWidth),k&&(a.height=e.minHeight),h&&(a.width=e.maxWidth),i&&(a.height=e.maxHeight);var l=this.originalPosition.left+this.originalSize.width,m=this.position.top+this.size.height,n=/sw|nw|w/.test(g),o=/nw|ne|n/.test(g);j&&n&&(a.left=l-e.minWidth),h&&n&&(a.left=l-e.maxWidth),k&&o&&(a.top=m-e.minHeight),i&&o&&(a.top=m-e.maxHeight);var p=!a.width&&!a.height;return p&&!a.left&&a.top?a.top=null:p&&!a.top&&a.left&&(a.left=null),a},_proportionallyResize:function(){var b=this.options;if(!this._proportionallyResizeElements.length)return;var c=this.helper||this.element;for(var d=0;d');var d=a.browser.msie&&a.browser.version<7,e=d?1:0,f=d?2:-1;this.helper.addClass(this._helper).css({width:this.element.outerWidth()+f,height:this.element.outerHeight()+f,position:"absolute",left:this.elementOffset.left-e+"px",top:this.elementOffset.top-e+"px",zIndex:++c.zIndex}),this.helper.appendTo("body").disableSelection()}else this.helper=this.element},_change:{e:function(a,b,c){return{width:this.originalSize.width+b}},w:function(a,b,c){var d=this.options,e=this.originalSize,f=this.originalPosition;return{left:f.left+b,width:e.width-b}},n:function(a,b,c){var d=this.options,e=this.originalSize,f=this.originalPosition;return{top:f.top+c,height:e.height-c}},s:function(a,b,c){return{height:this.originalSize.height+c}},se:function(b,c,d){return a.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[b,c,d]))},sw:function(b,c,d){return a.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[b,c,d]))},ne:function(b,c,d){return a.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[b,c,d]))},nw:function(b,c,d){return a.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[b,c,d]))}},_propagate:function(b,c){a.ui.plugin.call(this,b,[c,this.ui()]),b!="resize"&&this._trigger(b,c,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),a.extend(a.ui.resizable,{version:"1.8.19"}),a.ui.plugin.add("resizable","alsoResize",{start:function(b,c){var d=a(this).data("resizable"),e=d.options,f=function(b){a(b).each(function(){var b=a(this);b.data("resizable-alsoresize",{width:parseInt(b.width(),10),height:parseInt(b.height(),10),left:parseInt(b.css("left"),10),top:parseInt(b.css("top"),10)})})};typeof e.alsoResize=="object"&&!e.alsoResize.parentNode?e.alsoResize.length?(e.alsoResize=e.alsoResize[0],f(e.alsoResize)):a.each(e.alsoResize,function(a){f(a)}):f(e.alsoResize)},resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.originalSize,g=d.originalPosition,h={height:d.size.height-f.height||0,width:d.size.width-f.width||0,top:d.position.top-g.top||0,left:d.position.left-g.left||0},i=function(b,d){a(b).each(function(){var b=a(this),e=a(this).data("resizable-alsoresize"),f={},g=d&&d.length?d:b.parents(c.originalElement[0]).length?["width","height"]:["width","height","top","left"];a.each(g,function(a,b){var c=(e[b]||0)+(h[b]||0);c&&c>=0&&(f[b]=c||null)}),b.css(f)})};typeof e.alsoResize=="object"&&!e.alsoResize.nodeType?a.each(e.alsoResize,function(a,b){i(a,b)}):i(e.alsoResize)},stop:function(b,c){a(this).removeData("resizable-alsoresize")}}),a.ui.plugin.add("resizable","animate",{stop:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d._proportionallyResizeElements,g=f.length&&/textarea/i.test(f[0].nodeName),h=g&&a.ui.hasScroll(f[0],"left")?0:d.sizeDiff.height,i=g?0:d.sizeDiff.width,j={width:d.size.width-i,height:d.size.height-h},k=parseInt(d.element.css("left"),10)+(d.position.left-d.originalPosition.left)||null,l=parseInt(d.element.css("top"),10)+(d.position.top-d.originalPosition.top)||null;d.element.animate(a.extend(j,l&&k?{top:l,left:k}:{}),{duration:e.animateDuration,easing:e.animateEasing,step:function(){var c={width:parseInt(d.element.css("width"),10),height:parseInt(d.element.css("height"),10),top:parseInt(d.element.css("top"),10),left:parseInt(d.element.css("left"),10)};f&&f.length&&a(f[0]).css({width:c.width,height:c.height}),d._updateCache(c),d._propagate("resize",b)}})}}),a.ui.plugin.add("resizable","containment",{start:function(b,d){var e=a(this).data("resizable"),f=e.options,g=e.element,h=f.containment,i=h instanceof a?h.get(0):/parent/.test(h)?g.parent().get(0):h;if(!i)return;e.containerElement=a(i);if(/document/.test(h)||h==document)e.containerOffset={left:0,top:0},e.containerPosition={left:0,top:0},e.parentData={element:a(document),left:0,top:0,width:a(document).width(),height:a(document).height()||document.body.parentNode.scrollHeight};else{var j=a(i),k=[];a(["Top","Right","Left","Bottom"]).each(function(a,b){k[a]=c(j.css("padding"+b))}),e.containerOffset=j.offset(),e.containerPosition=j.position(),e.containerSize={height:j.innerHeight()-k[3],width:j.innerWidth()-k[1]};var l=e.containerOffset,m=e.containerSize.height,n=e.containerSize.width,o=a.ui.hasScroll(i,"left")?i.scrollWidth:n,p=a.ui.hasScroll(i)?i.scrollHeight:m;e.parentData={element:i,left:l.left,top:l.top,width:o,height:p}}},resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.containerSize,g=d.containerOffset,h=d.size,i=d.position,j=d._aspectRatio||b.shiftKey,k={top:0,left:0},l=d.containerElement;l[0]!=document&&/static/.test(l.css("position"))&&(k=g),i.left<(d._helper?g.left:0)&&(d.size.width=d.size.width+(d._helper?d.position.left-g.left:d.position.left-k.left),j&&(d.size.height=d.size.width/d.aspectRatio),d.position.left=e.helper?g.left:0),i.top<(d._helper?g.top:0)&&(d.size.height=d.size.height+(d._helper?d.position.top-g.top:d.position.top),j&&(d.size.width=d.size.height*d.aspectRatio),d.position.top=d._helper?g.top:0),d.offset.left=d.parentData.left+d.position.left,d.offset.top=d.parentData.top+d.position.top;var m=Math.abs((d._helper?d.offset.left-k.left:d.offset.left-k.left)+d.sizeDiff.width),n=Math.abs((d._helper?d.offset.top-k.top:d.offset.top-g.top)+d.sizeDiff.height),o=d.containerElement.get(0)==d.element.parent().get(0),p=/relative|absolute/.test(d.containerElement.css("position"));o&&p&&(m-=d.parentData.left),m+d.size.width>=d.parentData.width&&(d.size.width=d.parentData.width-m,j&&(d.size.height=d.size.width/d.aspectRatio)),n+d.size.height>=d.parentData.height&&(d.size.height=d.parentData.height-n,j&&(d.size.width=d.size.height*d.aspectRatio))},stop:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.position,g=d.containerOffset,h=d.containerPosition,i=d.containerElement,j=a(d.helper),k=j.offset(),l=j.outerWidth()-d.sizeDiff.width,m=j.outerHeight()-d.sizeDiff.height;d._helper&&!e.animate&&/relative/.test(i.css("position"))&&a(this).css({left:k.left-h.left-g.left,width:l,height:m}),d._helper&&!e.animate&&/static/.test(i.css("position"))&&a(this).css({left:k.left-h.left-g.left,width:l,height:m})}}),a.ui.plugin.add("resizable","ghost",{start:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.size;d.ghost=d.originalElement.clone(),d.ghost.css({opacity:.25,display:"block",position:"relative",height:f.height,width:f.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof e.ghost=="string"?e.ghost:""),d.ghost.appendTo(d.helper)},resize:function(b,c){var d=a(this).data("resizable"),e=d.options;d.ghost&&d.ghost.css({position:"relative",height:d.size.height,width:d.size.width})},stop:function(b,c){var d=a(this).data("resizable"),e=d.options;d.ghost&&d.helper&&d.helper.get(0).removeChild(d.ghost.get(0))}}),a.ui.plugin.add("resizable","grid",{resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.size,g=d.originalSize,h=d.originalPosition,i=d.axis,j=e._aspectRatio||b.shiftKey;e.grid=typeof e.grid=="number"?[e.grid,e.grid]:e.grid;var k=Math.round((f.width-g.width)/(e.grid[0]||1))*(e.grid[0]||1),l=Math.round((f.height-g.height)/(e.grid[1]||1))*(e.grid[1]||1);/^(se|s|e)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l):/^(ne)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l,d.position.top=h.top-l):/^(sw)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l,d.position.left=h.left-k):(d.size.width=g.width+k,d.size.height=g.height+l,d.position.top=h.top-l,d.position.left=h.left-k)}});var c=function(a){return parseInt(a,10)||0},d=function(a){return!isNaN(parseInt(a,10))}})(jQuery);/*! jQuery UI - v1.8.19 - 2012-04-16 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.selectable.js +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ +(function(a,b){a.widget("ui.selectable",a.ui.mouse,{options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch"},_create:function(){var b=this;this.element.addClass("ui-selectable"),this.dragged=!1;var c;this.refresh=function(){c=a(b.options.filter,b.element[0]),c.addClass("ui-selectee"),c.each(function(){var b=a(this),c=b.offset();a.data(this,"selectable-item",{element:this,$element:b,left:c.left,top:c.top,right:c.left+b.outerWidth(),bottom:c.top+b.outerHeight(),startselected:!1,selected:b.hasClass("ui-selected"),selecting:b.hasClass("ui-selecting"),unselecting:b.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=c.addClass("ui-selectee"),this._mouseInit(),this.helper=a("
")},destroy:function(){return this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable"),this._mouseDestroy(),this},_mouseStart:function(b){var c=this;this.opos=[b.pageX,b.pageY];if(this.options.disabled)return;var d=this.options;this.selectees=a(d.filter,this.element[0]),this._trigger("start",b),a(d.appendTo).append(this.helper),this.helper.css({left:b.clientX,top:b.clientY,width:0,height:0}),d.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var d=a.data(this,"selectable-item");d.startselected=!0,!b.metaKey&&!b.ctrlKey&&(d.$element.removeClass("ui-selected"),d.selected=!1,d.$element.addClass("ui-unselecting"),d.unselecting=!0,c._trigger("unselecting",b,{unselecting:d.element}))}),a(b.target).parents().andSelf().each(function(){var d=a.data(this,"selectable-item");if(d){var e=!b.metaKey&&!b.ctrlKey||!d.$element.hasClass("ui-selected");return d.$element.removeClass(e?"ui-unselecting":"ui-selected").addClass(e?"ui-selecting":"ui-unselecting"),d.unselecting=!e,d.selecting=e,d.selected=e,e?c._trigger("selecting",b,{selecting:d.element}):c._trigger("unselecting",b,{unselecting:d.element}),!1}})},_mouseDrag:function(b){var c=this;this.dragged=!0;if(this.options.disabled)return;var d=this.options,e=this.opos[0],f=this.opos[1],g=b.pageX,h=b.pageY;if(e>g){var i=g;g=e,e=i}if(f>h){var i=h;h=f,f=i}return this.helper.css({left:e,top:f,width:g-e,height:h-f}),this.selectees.each(function(){var i=a.data(this,"selectable-item");if(!i||i.element==c.element[0])return;var j=!1;d.tolerance=="touch"?j=!(i.left>g||i.righth||i.bottome&&i.rightf&&i.bottom *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3},_create:function(){var a=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?a.axis==="x"||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},destroy:function(){a.Widget.prototype.destroy.call(this),this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var b=this.items.length-1;b>=0;b--)this.items[b].item.removeData(this.widgetName+"-item");return this},_setOption:function(b,c){b==="disabled"?(this.options[b]=c,this.widget()[c?"addClass":"removeClass"]("ui-sortable-disabled")):a.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(b,c){var d=this;if(this.reverting)return!1;if(this.options.disabled||this.options.type=="static")return!1;this._refreshItems(b);var e=null,f=this,g=a(b.target).parents().each(function(){if(a.data(this,d.widgetName+"-item")==f)return e=a(this),!1});a.data(b.target,d.widgetName+"-item")==f&&(e=a(b.target));if(!e)return!1;if(this.options.handle&&!c){var h=!1;a(this.options.handle,e).find("*").andSelf().each(function(){this==b.target&&(h=!0)});if(!h)return!1}return this.currentItem=e,this._removeCurrentsFromItems(),!0},_mouseStart:function(b,c,d){var e=this.options,f=this;this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(b),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this._generatePosition(b),this.originalPageX=b.pageX,this.originalPageY=b.pageY,e.cursorAt&&this._adjustOffsetFromHelper(e.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!=this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),e.containment&&this._setContainment(),e.cursor&&(a("body").css("cursor")&&(this._storedCursor=a("body").css("cursor")),a("body").css("cursor",e.cursor)),e.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",e.opacity)),e.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",e.zIndex)),this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",b,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions();if(!d)for(var g=this.containers.length-1;g>=0;g--)this.containers[g]._trigger("activate",b,f._uiHash(this));return a.ui.ddmanager&&(a.ui.ddmanager.current=this),a.ui.ddmanager&&!e.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(b),!0},_mouseDrag:function(b){this.position=this._generatePosition(b),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){var c=this.options,d=!1;this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-b.pageY=0;e--){var f=this.items[e],g=f.item[0],h=this._intersectsWithPointer(f);if(!h)continue;if(g!=this.currentItem[0]&&this.placeholder[h==1?"next":"prev"]()[0]!=g&&!a.ui.contains(this.placeholder[0],g)&&(this.options.type=="semi-dynamic"?!a.ui.contains(this.element[0],g):!0)){this.direction=h==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(f))this._rearrange(b,f);else break;this._trigger("change",b,this._uiHash());break}}return this._contactContainers(b),a.ui.ddmanager&&a.ui.ddmanager.drag(this,b),this._trigger("sort",b,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(b,c){if(!b)return;a.ui.ddmanager&&!this.options.dropBehaviour&&a.ui.ddmanager.drop(this,b);if(this.options.revert){var d=this,e=d.placeholder.offset();d.reverting=!0,a(this.helper).animate({left:e.left-this.offset.parent.left-d.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:e.top-this.offset.parent.top-d.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){d._clear(b)})}else this._clear(b,c);return!1},cancel:function(){var b=this;if(this.dragging){this._mouseUp({target:null}),this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var c=this.containers.length-1;c>=0;c--)this.containers[c]._trigger("deactivate",null,b._uiHash(this)),this.containers[c].containerCache.over&&(this.containers[c]._trigger("out",null,b._uiHash(this)),this.containers[c].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),a.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?a(this.domPosition.prev).after(this.currentItem):a(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(b){var c=this._getItemsAsjQuery(b&&b.connected),d=[];return b=b||{},a(c).each(function(){var c=(a(b.item||this).attr(b.attribute||"id")||"").match(b.expression||/(.+)[-=_](.+)/);c&&d.push((b.key||c[1]+"[]")+"="+(b.key&&b.expression?c[1]:c[2]))}),!d.length&&b.key&&d.push(b.key+"="),d.join("&")},toArray:function(b){var c=this._getItemsAsjQuery(b&&b.connected),d=[];return b=b||{},c.each(function(){d.push(a(b.item||this).attr(b.attribute||"id")||"")}),d},_intersectsWith:function(a){var b=this.positionAbs.left,c=b+this.helperProportions.width,d=this.positionAbs.top,e=d+this.helperProportions.height,f=a.left,g=f+a.width,h=a.top,i=h+a.height,j=this.offset.click.top,k=this.offset.click.left,l=d+j>h&&d+jf&&b+ka[this.floating?"width":"height"]?l:f0?"down":"up")},_getDragHorizontalDirection:function(){var a=this.positionAbs.left-this.lastPositionAbs.left;return a!=0&&(a>0?"right":"left")},refresh:function(a){return this._refreshItems(a),this.refreshPositions(),this},_connectWith:function(){var a=this.options;return a.connectWith.constructor==String?[a.connectWith]:a.connectWith},_getItemsAsjQuery:function(b){var c=this,d=[],e=[],f=this._connectWith();if(f&&b)for(var g=f.length-1;g>=0;g--){var h=a(f[g]);for(var i=h.length-1;i>=0;i--){var j=a.data(h[i],this.widgetName);j&&j!=this&&!j.options.disabled&&e.push([a.isFunction(j.options.items)?j.options.items.call(j.element):a(j.options.items,j.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),j])}}e.push([a.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):a(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var g=e.length-1;g>=0;g--)e[g][0].each(function(){d.push(this)});return a(d)},_removeCurrentsFromItems:function(){var a=this.currentItem.find(":data("+this.widgetName+"-item)");for(var b=0;b=0;g--){var h=a(f[g]);for(var i=h.length-1;i>=0;i--){var j=a.data(h[i],this.widgetName);j&&j!=this&&!j.options.disabled&&(e.push([a.isFunction(j.options.items)?j.options.items.call(j.element[0],b,{item:this.currentItem}):a(j.options.items,j.element),j]),this.containers.push(j))}}for(var g=e.length-1;g>=0;g--){var k=e[g][1],l=e[g][0];for(var i=0,m=l.length;i=0;c--){var d=this.items[c];if(d.instance!=this.currentContainer&&this.currentContainer&&d.item[0]!=this.currentItem[0])continue;var e=this.options.toleranceElement?a(this.options.toleranceElement,d.item):d.item;b||(d.width=e.outerWidth(),d.height=e.outerHeight());var f=e.offset();d.left=f.left,d.top=f.top}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(var c=this.containers.length-1;c>=0;c--){var f=this.containers[c].element.offset();this.containers[c].containerCache.left=f.left,this.containers[c].containerCache.top=f.top,this.containers[c].containerCache.width=this.containers[c].element.outerWidth(),this.containers[c].containerCache.height=this.containers[c].element.outerHeight()}return this},_createPlaceholder:function(b){var c=b||this,d=c.options;if(!d.placeholder||d.placeholder.constructor==String){var e=d.placeholder;d.placeholder={element:function(){var b=a(document.createElement(c.currentItem[0].nodeName)).addClass(e||c.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper").html(" ")[0];return e||(b.style.visibility="hidden"),b},update:function(a,b){if(e&&!d.forcePlaceholderSize)return;b.height()||b.height(c.currentItem.innerHeight()-parseInt(c.currentItem.css("paddingTop")||0,10)-parseInt(c.currentItem.css("paddingBottom")||0,10)),b.width()||b.width(c.currentItem.innerWidth()-parseInt(c.currentItem.css("paddingLeft")||0,10)-parseInt(c.currentItem.css("paddingRight")||0,10))}}}c.placeholder=a(d.placeholder.element.call(c.element,c.currentItem)),c.currentItem.after(c.placeholder),d.placeholder.update(c,c.placeholder)},_contactContainers:function(b){var c=null,d=null;for(var e=this.containers.length-1;e>=0;e--){if(a.ui.contains(this.currentItem[0],this.containers[e].element[0]))continue;if(this._intersectsWith(this.containers[e].containerCache)){if(c&&a.ui.contains(this.containers[e].element[0],c.element[0]))continue;c=this.containers[e],d=e}else this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",b,this._uiHash(this)),this.containers[e].containerCache.over=0)}if(!c)return;if(this.containers.length===1)this.containers[d]._trigger("over",b,this._uiHash(this)),this.containers[d].containerCache.over=1;else if(this.currentContainer!=this.containers[d]){var f=1e4,g=null,h=this.positionAbs[this.containers[d].floating?"left":"top"];for(var i=this.items.length-1;i>=0;i--){if(!a.ui.contains(this.containers[d].element[0],this.items[i].item[0]))continue;var j=this.items[i][this.containers[d].floating?"left":"top"];Math.abs(j-h)this.containment[2]&&(f=this.containment[2]+this.offset.click.left),b.pageY-this.offset.click.top>this.containment[3]&&(g=this.containment[3]+this.offset.click.top));if(c.grid){var h=this.originalPageY+Math.round((g-this.originalPageY)/c.grid[1])*c.grid[1];g=this.containment?h-this.offset.click.topthis.containment[3]?h-this.offset.click.topthis.containment[2]?i-this.offset.click.left=0;f--)a.ui.contains(this.containers[f].element[0],this.currentItem[0])&&!c&&(d.push(function(a){return function(b){a._trigger("receive",b,this._uiHash(this))}}.call(this,this.containers[f])),d.push(function(a){return function(b){a._trigger("update",b,this._uiHash(this))}}.call(this,this.containers[f])))}for(var f=this.containers.length-1;f>=0;f--)c||d.push(function(a){return function(b){a._trigger("deactivate",b,this._uiHash(this))}}.call(this,this.containers[f])),this.containers[f].containerCache.over&&(d.push(function(a){return function(b){a._trigger("out",b,this._uiHash(this))}}.call(this,this.containers[f])),this.containers[f].containerCache.over=0);this._storedCursor&&a("body").css("cursor",this._storedCursor),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex),this.dragging=!1;if(this.cancelHelperRemoval){if(!c){this._trigger("beforeStop",b,this._uiHash());for(var f=0;f li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:!1,navigationFilter:function(){return this.href.toLowerCase()===location.href.toLowerCase()}},_create:function(){var b=this,c=b.options;b.running=0,b.element.addClass("ui-accordion ui-widget ui-helper-reset").children("li").addClass("ui-accordion-li-fix"),b.headers=b.element.find(c.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){if(c.disabled)return;a(this).addClass("ui-state-hover")}).bind("mouseleave.accordion",function(){if(c.disabled)return;a(this).removeClass("ui-state-hover")}).bind("focus.accordion",function(){if(c.disabled)return;a(this).addClass("ui-state-focus")}).bind("blur.accordion",function(){if(c.disabled)return;a(this).removeClass("ui-state-focus")}),b.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");if(c.navigation){var d=b.element.find("a").filter(c.navigationFilter).eq(0);if(d.length){var e=d.closest(".ui-accordion-header");e.length?b.active=e:b.active=d.closest(".ui-accordion-content").prev()}}b.active=b._findActive(b.active||c.active).addClass("ui-state-default ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top"),b.active.next().addClass("ui-accordion-content-active"),b._createIcons(),b.resize(),b.element.attr("role","tablist"),b.headers.attr("role","tab").bind("keydown.accordion",function(a){return b._keydown(a)}).next().attr("role","tabpanel"),b.headers.not(b.active||"").attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).next().hide(),b.active.length?b.active.attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}):b.headers.eq(0).attr("tabIndex",0),a.browser.safari||b.headers.find("a").attr("tabIndex",-1),c.event&&b.headers.bind(c.event.split(" ").join(".accordion ")+".accordion",function(a){b._clickHandler.call(b,a,this),a.preventDefault()})},_createIcons:function(){var b=this.options;b.icons&&(a("").addClass("ui-icon "+b.icons.header).prependTo(this.headers),this.active.children(".ui-icon").toggleClass(b.icons.header).toggleClass(b.icons.headerSelected),this.element.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.children(".ui-icon").remove(),this.element.removeClass("ui-accordion-icons")},destroy:function(){var b=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-accordion-disabled ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("tabIndex"),this.headers.find("a").removeAttr("tabIndex"),this._destroyIcons();var c=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-accordion-disabled ui-state-disabled");return(b.autoHeight||b.fillHeight)&&c.css("height",""),a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments),b=="active"&&this.activate(c),b=="icons"&&(this._destroyIcons(),c&&this._createIcons()),b=="disabled"&&this.headers.add(this.headers.next())[c?"addClass":"removeClass"]("ui-accordion-disabled ui-state-disabled")},_keydown:function(b){if(this.options.disabled||b.altKey||b.ctrlKey)return;var c=a.ui.keyCode,d=this.headers.length,e=this.headers.index(b.target),f=!1;switch(b.keyCode){case c.RIGHT:case c.DOWN:f=this.headers[(e+1)%d];break;case c.LEFT:case c.UP:f=this.headers[(e-1+d)%d];break;case c.SPACE:case c.ENTER:this._clickHandler({target:b.target},b.target),b.preventDefault()}return f?(a(b.target).attr("tabIndex",-1),a(f).attr("tabIndex",0),f.focus(),!1):!0},resize:function(){var b=this.options,c;if(b.fillSpace){if(a.browser.msie){var d=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden")}c=this.element.parent().height(),a.browser.msie&&this.element.parent().css("overflow",d),this.headers.each(function(){c-=a(this).outerHeight(!0)}),this.headers.next().each(function(){a(this).height(Math.max(0,c-a(this).innerHeight()+a(this).height()))}).css("overflow","auto")}else b.autoHeight&&(c=0,this.headers.next().each(function(){c=Math.max(c,a(this).height("").height())}).height(c));return this},activate:function(a){this.options.active=a;var b=this._findActive(a)[0];return this._clickHandler({target:b},b),this},_findActive:function(b){return b?typeof b=="number"?this.headers.filter(":eq("+b+")"):this.headers.not(this.headers.not(b)):b===!1?a([]):this.headers.filter(":eq(0)")},_clickHandler:function(b,c){var d=this.options;if(d.disabled)return;if(!b.target){if(!d.collapsible)return;this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header),this.active.next().addClass("ui-accordion-content-active");var e=this.active.next(),f={options:d,newHeader:a([]),oldHeader:d.active,newContent:a([]),oldContent:e},g=this.active=a([]);this._toggle(g,e,f);return}var h=a(b.currentTarget||c),i=h[0]===this.active[0];d.active=d.collapsible&&i?!1:this.headers.index(h);if(this.running||!d.collapsible&&i)return;var j=this.active,g=h.next(),e=this.active.next(),f={options:d,newHeader:i&&d.collapsible?a([]):h,oldHeader:this.active,newContent:i&&d.collapsible?a([]):g,oldContent:e},k=this.headers.index(this.active[0])>this.headers.index(h[0]);this.active=i?a([]):h,this._toggle(g,e,f,i,k),j.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header),i||(h.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").children(".ui-icon").removeClass(d.icons.header).addClass(d.icons.headerSelected),h.next().addClass("ui-accordion-content-active"));return},_toggle:function(b,c,d,e,f){var g=this,h=g.options;g.toShow=b,g.toHide=c,g.data=d;var i=function(){if(!g)return;return g._completed.apply(g,arguments)};g._trigger("changestart",null,g.data),g.running=c.size()===0?b.size():c.size();if(h.animated){var j={};h.collapsible&&e?j={toShow:a([]),toHide:c,complete:i,down:f,autoHeight:h.autoHeight||h.fillSpace}:j={toShow:b,toHide:c,complete:i,down:f,autoHeight:h.autoHeight||h.fillSpace},h.proxied||(h.proxied=h.animated),h.proxiedDuration||(h.proxiedDuration=h.duration),h.animated=a.isFunction(h.proxied)?h.proxied(j):h.proxied,h.duration=a.isFunction(h.proxiedDuration)?h.proxiedDuration(j):h.proxiedDuration;var k=a.ui.accordion.animations,l=h.duration,m=h.animated;m&&!k[m]&&!a.easing[m]&&(m="slide"),k[m]||(k[m]=function(a){this.slide(a,{easing:m,duration:l||700})}),k[m](j)}else h.collapsible&&e?b.toggle():(c.hide(),b.show()),i(!0);c.prev().attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).blur(),b.prev().attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}).focus()},_completed:function(a){this.running=a?0:--this.running;if(this.running)return;this.options.clearStyle&&this.toShow.add(this.toHide).css({height:"",overflow:""}),this.toHide.removeClass("ui-accordion-content-active"),this.toHide.length&&(this.toHide.parent()[0].className=this.toHide.parent()[0].className),this._trigger("change",null,this.data)}}),a.extend(a.ui.accordion,{version:"1.8.19",animations:{slide:function(b,c){b=a.extend({easing:"swing",duration:300},b,c);if(!b.toHide.size()){b.toShow.animate({height:"show",paddingTop:"show",paddingBottom:"show"},b);return}if(!b.toShow.size()){b.toHide.animate({height:"hide",paddingTop:"hide",paddingBottom:"hide"},b);return}var d=b.toShow.css("overflow"),e=0,f={},g={},h=["height","paddingTop","paddingBottom"],i,j=b.toShow;i=j[0].style.width,j.width(j.parent().width()-parseFloat(j.css("paddingLeft"))-parseFloat(j.css("paddingRight"))-(parseFloat(j.css("borderLeftWidth"))||0)-(parseFloat(j.css("borderRightWidth"))||0)),a.each(h,function(c,d){g[d]="hide";var e=(""+a.css(b.toShow[0],d)).match(/^([\d+-.]+)(.*)$/);f[d]={value:e[1],unit:e[2]||"px"}}),b.toShow.css({height:0,overflow:"hidden"}).show(),b.toHide.filter(":hidden").each(b.complete).end().filter(":visible").animate(g,{step:function(a,c){c.prop=="height"&&(e=c.end-c.start===0?0:(c.now-c.start)/(c.end-c.start)),b.toShow[0].style[c.prop]=e*f[c.prop].value+f[c.prop].unit},duration:b.duration,easing:b.easing,complete:function(){b.autoHeight||b.toShow.css("height",""),b.toShow.css({width:i,overflow:d}),b.complete()}})},bounceslide:function(a){this.slide(a,{easing:a.down?"easeOutBounce":"swing",duration:a.down?1e3:200})}}})})(jQuery);/*! jQuery UI - v1.8.19 - 2012-04-16 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.autocomplete.js +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ +(function(a,b){var c=0;a.widget("ui.autocomplete",{options:{appendTo:"body",autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null},pending:0,_create:function(){var b=this,c=this.element[0].ownerDocument,d;this.isMultiLine=this.element.is("textarea"),this.element.addClass("ui-autocomplete-input").attr("autocomplete","off").attr({role:"textbox","aria-autocomplete":"list","aria-haspopup":"true"}).bind("keydown.autocomplete",function(c){if(b.options.disabled||b.element.propAttr("readOnly"))return;d=!1;var e=a.ui.keyCode;switch(c.keyCode){case e.PAGE_UP:b._move("previousPage",c);break;case e.PAGE_DOWN:b._move("nextPage",c);break;case e.UP:b._keyEvent("previous",c);break;case e.DOWN:b._keyEvent("next",c);break;case e.ENTER:case e.NUMPAD_ENTER:b.menu.active&&(d=!0,c.preventDefault());case e.TAB:if(!b.menu.active)return;b.menu.select(c);break;case e.ESCAPE:b.element.val(b.term),b.close(c);break;default:clearTimeout(b.searching),b.searching=setTimeout(function(){b.term!=b.element.val()&&(b.selectedItem=null,b.search(null,c))},b.options.delay)}}).bind("keypress.autocomplete",function(a){d&&(d=!1,a.preventDefault())}).bind("focus.autocomplete",function(){if(b.options.disabled)return;b.selectedItem=null,b.previous=b.element.val()}).bind("blur.autocomplete",function(a){if(b.options.disabled)return;clearTimeout(b.searching),b.closing=setTimeout(function(){b.close(a),b._change(a)},150)}),this._initSource(),this.menu=a("
    ").addClass("ui-autocomplete").appendTo(a(this.options.appendTo||"body",c)[0]).mousedown(function(c){var d=b.menu.element[0];a(c.target).closest(".ui-menu-item").length||setTimeout(function(){a(document).one("mousedown",function(c){c.target!==b.element[0]&&c.target!==d&&!a.ui.contains(d,c.target)&&b.close()})},1),setTimeout(function(){clearTimeout(b.closing)},13)}).menu({focus:function(a,c){var d=c.item.data("item.autocomplete");!1!==b._trigger("focus",a,{item:d})&&/^key/.test(a.originalEvent.type)&&b.element.val(d.value)},selected:function(a,d){var e=d.item.data("item.autocomplete"),f=b.previous;b.element[0]!==c.activeElement&&(b.element.focus(),b.previous=f,setTimeout(function(){b.previous=f,b.selectedItem=e},1)),!1!==b._trigger("select",a,{item:e})&&b.element.val(e.value),b.term=b.element.val(),b.close(a),b.selectedItem=e},blur:function(a,c){b.menu.element.is(":visible")&&b.element.val()!==b.term&&b.element.val(b.term)}}).zIndex(this.element.zIndex()+1).css({top:0,left:0}).hide().data("menu"),a.fn.bgiframe&&this.menu.element.bgiframe(),b.beforeunloadHandler=function(){b.element.removeAttr("autocomplete")},a(window).bind("beforeunload",b.beforeunloadHandler)},destroy:function(){this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete").removeAttr("role").removeAttr("aria-autocomplete").removeAttr("aria-haspopup"),this.menu.element.remove(),a(window).unbind("beforeunload",this.beforeunloadHandler),a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments),b==="source"&&this._initSource(),b==="appendTo"&&this.menu.element.appendTo(a(c||"body",this.element[0].ownerDocument)[0]),b==="disabled"&&c&&this.xhr&&this.xhr.abort()},_initSource:function(){var b=this,c,d;a.isArray(this.options.source)?(c=this.options.source,this.source=function(b,d){d(a.ui.autocomplete.filter(c,b.term))}):typeof this.options.source=="string"?(d=this.options.source,this.source=function(c,e){b.xhr&&b.xhr.abort(),b.xhr=a.ajax({url:d,data:c,dataType:"json",success:function(a,b){e(a)},error:function(){e([])}})}):this.source=this.options.source},search:function(a,b){a=a!=null?a:this.element.val(),this.term=this.element.val();if(a.length").data("item.autocomplete",c).append(a("").text(c.label)).appendTo(b)},_move:function(a,b){if(!this.menu.element.is(":visible")){this.search(null,b);return}if(this.menu.first()&&/^previous/.test(a)||this.menu.last()&&/^next/.test(a)){this.element.val(this.term),this.menu.deactivate();return}this.menu[a](b)},widget:function(){return this.menu.element},_keyEvent:function(a,b){if(!this.isMultiLine||this.menu.element.is(":visible"))this._move(a,b),b.preventDefault()}}),a.extend(a.ui.autocomplete,{escapeRegex:function(a){return a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},filter:function(b,c){var d=new RegExp(a.ui.autocomplete.escapeRegex(c),"i");return a.grep(b,function(a){return d.test(a.label||a.value||a)})}})})(jQuery),function(a){a.widget("ui.menu",{_create:function(){var b=this;this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr({role:"listbox","aria-activedescendant":"ui-active-menuitem"}).click(function(c){if(!a(c.target).closest(".ui-menu-item a").length)return;c.preventDefault(),b.select(c)}),this.refresh()},refresh:function(){var b=this,c=this.element.children("li:not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","menuitem");c.children("a").addClass("ui-corner-all").attr("tabindex",-1).mouseenter(function(c){b.activate(c,a(this).parent())}).mouseleave(function(){b.deactivate()})},activate:function(a,b){this.deactivate();if(this.hasScroll()){var c=b.offset().top-this.element.offset().top,d=this.element.scrollTop(),e=this.element.height();c<0?this.element.scrollTop(d+c):c>=e&&this.element.scrollTop(d+c-e+b.height())}this.active=b.eq(0).children("a").addClass("ui-state-hover").attr("id","ui-active-menuitem").end(),this._trigger("focus",a,{item:b})},deactivate:function(){if(!this.active)return;this.active.children("a").removeClass("ui-state-hover").removeAttr("id"),this._trigger("blur"),this.active=null},next:function(a){this.move("next",".ui-menu-item:first",a)},previous:function(a){this.move("prev",".ui-menu-item:last",a)},first:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},last:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},move:function(a,b,c){if(!this.active){this.activate(c,this.element.children(b));return}var d=this.active[a+"All"](".ui-menu-item").eq(0);d.length?this.activate(c,d):this.activate(c,this.element.children(b))},nextPage:function(b){if(this.hasScroll()){if(!this.active||this.last()){this.activate(b,this.element.children(".ui-menu-item:first"));return}var c=this.active.offset().top,d=this.element.height(),e=this.element.children(".ui-menu-item").filter(function(){var b=a(this).offset().top-c-d+a(this).height();return b<10&&b>-10});e.length||(e=this.element.children(".ui-menu-item:last")),this.activate(b,e)}else this.activate(b,this.element.children(".ui-menu-item").filter(!this.active||this.last()?":first":":last"))},previousPage:function(b){if(this.hasScroll()){if(!this.active||this.first()){this.activate(b,this.element.children(".ui-menu-item:last"));return}var c=this.active.offset().top,d=this.element.height(),e=this.element.children(".ui-menu-item").filter(function(){var b=a(this).offset().top-c+d-a(this).height();return b<10&&b>-10});e.length||(e=this.element.children(".ui-menu-item:first")),this.activate(b,e)}else this.activate(b,this.element.children(".ui-menu-item").filter(!this.active||this.first()?":last":":first"))},hasScroll:function(){return this.element.height()",this.element[0].ownerDocument).addClass("ui-button-text").html(this.options.label).appendTo(b.empty()).text(),d=this.options.icons,e=d.primary&&d.secondary,f=[];d.primary||d.secondary?(this.options.text&&f.push("ui-button-text-icon"+(e?"s":d.primary?"-primary":"-secondary")),d.primary&&b.prepend(""),d.secondary&&b.append(""),this.options.text||(f.push(e?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||b.attr("title",c))):f.push("ui-button-text-only"),b.addClass(f.join(" "))}}),a.widget("ui.buttonset",{options:{items:":button, :submit, :reset, :checkbox, :radio, a, :data(button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(b,c){b==="disabled"&&this.buttons.button("option",b,c),a.Widget.prototype._setOption.apply(this,arguments)},refresh:function(){var b=this.element.css("direction")==="rtl";this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(b?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(b?"ui-corner-left":"ui-corner-right").end().end()},destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy"),a.Widget.prototype.destroy.call(this)}})})(jQuery);/*! jQuery UI - v1.8.19 - 2012-04-16 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.dialog.js +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ +(function(a,b){var c="ui-dialog ui-widget ui-widget-content ui-corner-all ",d={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},e={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},f=a.attrFn||{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0,click:!0};a.widget("ui.dialog",{options:{autoOpen:!0,buttons:{},closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:!1,maxWidth:!1,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",collision:"fit",using:function(b){var c=a(this).css(b).offset().top;c<0&&a(this).css("top",b.top-c)}},resizable:!0,show:null,stack:!0,title:"",width:300,zIndex:1e3},_create:function(){this.originalTitle=this.element.attr("title"),typeof this.originalTitle!="string"&&(this.originalTitle=""),this.options.title=this.options.title||this.originalTitle;var b=this,d=b.options,e=d.title||" ",f=a.ui.dialog.getTitleId(b.element),g=(b.uiDialog=a("
    ")).appendTo(document.body).hide().addClass(c+d.dialogClass).css({zIndex:d.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(c){d.closeOnEscape&&!c.isDefaultPrevented()&&c.keyCode&&c.keyCode===a.ui.keyCode.ESCAPE&&(b.close(c),c.preventDefault())}).attr({role:"dialog","aria-labelledby":f}).mousedown(function(a){b.moveToTop(!1,a)}),h=b.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(g),i=(b.uiDialogTitlebar=a("
    ")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(g),j=a('').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){j.addClass("ui-state-hover")},function(){j.removeClass("ui-state-hover")}).focus(function(){j.addClass("ui-state-focus")}).blur(function(){j.removeClass("ui-state-focus")}).click(function(a){return b.close(a),!1}).appendTo(i),k=(b.uiDialogTitlebarCloseText=a("")).addClass("ui-icon ui-icon-closethick").text(d.closeText).appendTo(j),l=a("").addClass("ui-dialog-title").attr("id",f).html(e).prependTo(i);a.isFunction(d.beforeclose)&&!a.isFunction(d.beforeClose)&&(d.beforeClose=d.beforeclose),i.find("*").add(i).disableSelection(),d.draggable&&a.fn.draggable&&b._makeDraggable(),d.resizable&&a.fn.resizable&&b._makeResizable(),b._createButtons(d.buttons),b._isOpen=!1,a.fn.bgiframe&&g.bgiframe()},_init:function(){this.options.autoOpen&&this.open()},destroy:function(){var a=this;return a.overlay&&a.overlay.destroy(),a.uiDialog.hide(),a.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body"),a.uiDialog.remove(),a.originalTitle&&a.element.attr("title",a.originalTitle),a},widget:function(){return this.uiDialog},close:function(b){var c=this,d,e;if(!1===c._trigger("beforeClose",b))return;return c.overlay&&c.overlay.destroy(),c.uiDialog.unbind("keypress.ui-dialog"),c._isOpen=!1,c.options.hide?c.uiDialog.hide(c.options.hide,function(){c._trigger("close",b)}):(c.uiDialog.hide(),c._trigger("close",b)),a.ui.dialog.overlay.resize(),c.options.modal&&(d=0,a(".ui-dialog").each(function(){this!==c.uiDialog[0]&&(e=a(this).css("z-index"),isNaN(e)||(d=Math.max(d,e)))}),a.ui.dialog.maxZ=d),c},isOpen:function(){return this._isOpen},moveToTop:function(b,c){var d=this,e=d.options,f;return e.modal&&!b||!e.stack&&!e.modal?d._trigger("focus",c):(e.zIndex>a.ui.dialog.maxZ&&(a.ui.dialog.maxZ=e.zIndex),d.overlay&&(a.ui.dialog.maxZ+=1,d.overlay.$el.css("z-index",a.ui.dialog.overlay.maxZ=a.ui.dialog.maxZ)),f={scrollTop:d.element.scrollTop(),scrollLeft:d.element.scrollLeft()},a.ui.dialog.maxZ+=1,d.uiDialog.css("z-index",a.ui.dialog.maxZ),d.element.attr(f),d._trigger("focus",c),d)},open:function(){if(this._isOpen)return;var b=this,c=b.options,d=b.uiDialog;return b.overlay=c.modal?new a.ui.dialog.overlay(b):null,b._size(),b._position(c.position),d.show(c.show),b.moveToTop(!0),c.modal&&d.bind("keydown.ui-dialog",function(b){if(b.keyCode!==a.ui.keyCode.TAB)return;var c=a(":tabbable",this),d=c.filter(":first"),e=c.filter(":last");if(b.target===e[0]&&!b.shiftKey)return d.focus(1),!1;if(b.target===d[0]&&b.shiftKey)return e.focus(1),!1}),a(b.element.find(":tabbable").get().concat(d.find(".ui-dialog-buttonpane :tabbable").get().concat(d.get()))).eq(0).focus(),b._isOpen=!0,b._trigger("open"),b},_createButtons:function(b){var c=this,d=!1,e=a("
    ").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),g=a("
    ").addClass("ui-dialog-buttonset").appendTo(e);c.uiDialog.find(".ui-dialog-buttonpane").remove(),typeof b=="object"&&b!==null&&a.each(b,function(){return!(d=!0)}),d&&(a.each(b,function(b,d){d=a.isFunction(d)?{click:d,text:b}:d;var e=a('').click(function(){d.click.apply(c.element[0],arguments)}).appendTo(g);a.each(d,function(a,b){if(a==="click")return;a in f?e[a](b):e.attr(a,b)}),a.fn.button&&e.button()}),e.appendTo(c.uiDialog))},_makeDraggable:function(){function f(a){return{position:a.position,offset:a.offset}}var b=this,c=b.options,d=a(document),e;b.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(d,g){e=c.height==="auto"?"auto":a(this).height(),a(this).height(a(this).height()).addClass("ui-dialog-dragging"),b._trigger("dragStart",d,f(g))},drag:function(a,c){b._trigger("drag",a,f(c))},stop:function(g,h){c.position=[h.position.left-d.scrollLeft(),h.position.top-d.scrollTop()],a(this).removeClass("ui-dialog-dragging").height(e),b._trigger("dragStop",g,f(h)),a.ui.dialog.overlay.resize()}})},_makeResizable:function(c){function h(a){return{originalPosition:a.originalPosition,originalSize:a.originalSize,position:a.position,size:a.size}}c=c===b?this.options.resizable:c;var d=this,e=d.options,f=d.uiDialog.css("position"),g=typeof c=="string"?c:"n,e,s,w,se,sw,ne,nw";d.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:d.element,maxWidth:e.maxWidth,maxHeight:e.maxHeight,minWidth:e.minWidth,minHeight:d._minHeight(),handles:g,start:function(b,c){a(this).addClass("ui-dialog-resizing"),d._trigger("resizeStart",b,h(c))},resize:function(a,b){d._trigger("resize",a,h(b))},stop:function(b,c){a(this).removeClass("ui-dialog-resizing"),e.height=a(this).height(),e.width=a(this).width(),d._trigger("resizeStop",b,h(c)),a.ui.dialog.overlay.resize()}}).css("position",f).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var a=this.options;return a.height==="auto"?a.minHeight:Math.min(a.minHeight,a.height)},_position:function(b){var c=[],d=[0,0],e;if(b){if(typeof b=="string"||typeof b=="object"&&"0"in b)c=b.split?b.split(" "):[b[0],b[1]],c.length===1&&(c[1]=c[0]),a.each(["left","top"],function(a,b){+c[a]===c[a]&&(d[a]=c[a],c[a]=b)}),b={my:c.join(" "),at:c.join(" "),offset:d.join(" ")};b=a.extend({},a.ui.dialog.prototype.options.position,b)}else b=a.ui.dialog.prototype.options.position;e=this.uiDialog.is(":visible"),e||this.uiDialog.show(),this.uiDialog.css({top:0,left:0}).position(a.extend({of:window},b)),e||this.uiDialog.hide()},_setOptions:function(b){var c=this,f={},g=!1;a.each(b,function(a,b){c._setOption(a,b),a in d&&(g=!0),a in e&&(f[a]=b)}),g&&this._size(),this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option",f)},_setOption:function(b,d){var e=this,f=e.uiDialog;switch(b){case"beforeclose":b="beforeClose";break;case"buttons":e._createButtons(d);break;case"closeText":e.uiDialogTitlebarCloseText.text(""+d);break;case"dialogClass":f.removeClass(e.options.dialogClass).addClass(c+d);break;case"disabled":d?f.addClass("ui-dialog-disabled"):f.removeClass("ui-dialog-disabled");break;case"draggable":var g=f.is(":data(draggable)");g&&!d&&f.draggable("destroy"),!g&&d&&e._makeDraggable();break;case"position":e._position(d);break;case"resizable":var h=f.is(":data(resizable)");h&&!d&&f.resizable("destroy"),h&&typeof d=="string"&&f.resizable("option","handles",d),!h&&d!==!1&&e._makeResizable(d);break;case"title":a(".ui-dialog-title",e.uiDialogTitlebar).html(""+(d||" "))}a.Widget.prototype._setOption.apply(e,arguments)},_size:function(){var b=this.options,c,d,e=this.uiDialog.is(":visible");this.element.show().css({width:"auto",minHeight:0,height:0}),b.minWidth>b.width&&(b.width=b.minWidth),c=this.uiDialog.css({height:"auto",width:b.width}).height(),d=Math.max(0,b.minHeight-c);if(b.height==="auto")if(a.support.minHeight)this.element.css({minHeight:d,height:"auto"});else{this.uiDialog.show();var f=this.element.css("height","auto").height();e||this.uiDialog.hide(),this.element.height(Math.max(f,d))}else this.element.height(Math.max(b.height-c,0));this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())}}),a.extend(a.ui.dialog,{version:"1.8.19",uuid:0,maxZ:0,getTitleId:function(a){var b=a.attr("id");return b||(this.uuid+=1,b=this.uuid),"ui-dialog-title-"+b},overlay:function(b){this.$el=a.ui.dialog.overlay.create(b)}}),a.extend(a.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:a.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(a){return a+".dialog-overlay"}).join(" "),create:function(b){this.instances.length===0&&(setTimeout(function(){a.ui.dialog.overlay.instances.length&&a(document).bind(a.ui.dialog.overlay.events,function(b){if(a(b.target).zIndex()").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),height:this.height()});return a.fn.bgiframe&&c.bgiframe(),this.instances.push(c),c},destroy:function(b){var c=a.inArray(b,this.instances);c!=-1&&this.oldInstances.push(this.instances.splice(c,1)[0]),this.instances.length===0&&a([document,window]).unbind(".dialog-overlay"),b.remove();var d=0;a.each(this.instances,function(){d=Math.max(d,this.css("z-index"))}),this.maxZ=d},height:function(){var b,c;return a.browser.msie&&a.browser.version<7?(b=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight),c=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight),b",remove:null,select:null,show:null,spinner:"Loading…",tabTemplate:"
  • #{label}
  • "},_create:function(){this._tabify(!0)},_setOption:function(a,b){if(a=="selected"){if(this.options.collapsible&&b==this.options.selected)return;this.select(b)}else this.options[a]=b,this._tabify()},_tabId:function(a){return a.title&&a.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF-]/g,"")||this.options.idPrefix+e()},_sanitizeSelector:function(a){return a.replace(/:/g,"\\:")},_cookie:function(){var b=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+f());return a.cookie.apply(null,[b].concat(a.makeArray(arguments)))},_ui:function(a,b){return{tab:a,panel:b,index:this.anchors.index(a)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var b=a(this);b.html(b.data("label.tabs")).removeData("label.tabs")})},_tabify:function(c){function m(b,c){b.css("display",""),!a.support.opacity&&c.opacity&&b[0].style.removeAttribute("filter")}var d=this,e=this.options,f=/^#.+/;this.list=this.element.find("ol,ul").eq(0),this.lis=a(" > li:has(a[href])",this.list),this.anchors=this.lis.map(function(){return a("a",this)[0]}),this.panels=a([]),this.anchors.each(function(b,c){var g=a(c).attr("href"),h=g.split("#")[0],i;h&&(h===location.toString().split("#")[0]||(i=a("base")[0])&&h===i.href)&&(g=c.hash,c.href=g);if(f.test(g))d.panels=d.panels.add(d.element.find(d._sanitizeSelector(g)));else if(g&&g!=="#"){a.data(c,"href.tabs",g),a.data(c,"load.tabs",g.replace(/#.*$/,""));var j=d._tabId(c);c.href="#"+j;var k=d.element.find("#"+j);k.length||(k=a(e.panelTemplate).attr("id",j).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(d.panels[b-1]||d.list),k.data("destroy.tabs",!0)),d.panels=d.panels.add(k)}else e.disabled.push(b)}),c?(this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all"),this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"),this.lis.addClass("ui-state-default ui-corner-top"),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom"),e.selected===b?(location.hash&&this.anchors.each(function(a,b){if(b.hash==location.hash)return e.selected=a,!1}),typeof e.selected!="number"&&e.cookie&&(e.selected=parseInt(d._cookie(),10)),typeof e.selected!="number"&&this.lis.filter(".ui-tabs-selected").length&&(e.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))),e.selected=e.selected||(this.lis.length?0:-1)):e.selected===null&&(e.selected=-1),e.selected=e.selected>=0&&this.anchors[e.selected]||e.selected<0?e.selected:0,e.disabled=a.unique(e.disabled.concat(a.map(this.lis.filter(".ui-state-disabled"),function(a,b){return d.lis.index(a)}))).sort(),a.inArray(e.selected,e.disabled)!=-1&&e.disabled.splice(a.inArray(e.selected,e.disabled),1),this.panels.addClass("ui-tabs-hide"),this.lis.removeClass("ui-tabs-selected ui-state-active"),e.selected>=0&&this.anchors.length&&(d.element.find(d._sanitizeSelector(d.anchors[e.selected].hash)).removeClass("ui-tabs-hide"),this.lis.eq(e.selected).addClass("ui-tabs-selected ui-state-active"),d.element.queue("tabs",function(){d._trigger("show",null,d._ui(d.anchors[e.selected],d.element.find(d._sanitizeSelector(d.anchors[e.selected].hash))[0]))}),this.load(e.selected)),a(window).bind("unload",function(){d.lis.add(d.anchors).unbind(".tabs"),d.lis=d.anchors=d.panels=null})):e.selected=this.lis.index(this.lis.filter(".ui-tabs-selected")),this.element[e.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible"),e.cookie&&this._cookie(e.selected,e.cookie);for(var g=0,h;h=this.lis[g];g++)a(h)[a.inArray(g,e.disabled)!=-1&&!a(h).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");e.cache===!1&&this.anchors.removeData("cache.tabs"),this.lis.add(this.anchors).unbind(".tabs");if(e.event!=="mouseover"){var i=function(a,b){b.is(":not(.ui-state-disabled)")&&b.addClass("ui-state-"+a)},j=function(a,b){b.removeClass("ui-state-"+a)};this.lis.bind("mouseover.tabs",function(){i("hover",a(this))}),this.lis.bind("mouseout.tabs",function(){j("hover",a(this))}),this.anchors.bind("focus.tabs",function(){i("focus",a(this).closest("li"))}),this.anchors.bind("blur.tabs",function(){j("focus",a(this).closest("li"))})}var k,l;e.fx&&(a.isArray(e.fx)?(k=e.fx[0],l=e.fx[1]):k=l=e.fx);var n=l?function(b,c){a(b).closest("li").addClass("ui-tabs-selected ui-state-active"),c.hide().removeClass("ui-tabs-hide").animate(l,l.duration||"normal",function(){m(c,l),d._trigger("show",null,d._ui(b,c[0]))})}:function(b,c){a(b).closest("li").addClass("ui-tabs-selected ui-state-active"),c.removeClass("ui-tabs-hide"),d._trigger("show",null,d._ui(b,c[0]))},o=k?function(a,b){b.animate(k,k.duration||"normal",function(){d.lis.removeClass("ui-tabs-selected ui-state-active"),b.addClass("ui-tabs-hide"),m(b,k),d.element.dequeue("tabs")})}:function(a,b,c){d.lis.removeClass("ui-tabs-selected ui-state-active"),b.addClass("ui-tabs-hide"),d.element.dequeue("tabs")};this.anchors.bind(e.event+".tabs",function(){var b=this,c=a(b).closest("li"),f=d.panels.filter(":not(.ui-tabs-hide)"),g=d.element.find(d._sanitizeSelector(b.hash));if(c.hasClass("ui-tabs-selected")&&!e.collapsible||c.hasClass("ui-state-disabled")||c.hasClass("ui-state-processing")||d.panels.filter(":animated").length||d._trigger("select",null,d._ui(this,g[0]))===!1)return this.blur(),!1;e.selected=d.anchors.index(this),d.abort();if(e.collapsible){if(c.hasClass("ui-tabs-selected"))return e.selected=-1,e.cookie&&d._cookie(e.selected,e.cookie),d.element.queue("tabs",function(){o(b,f)}).dequeue("tabs"),this.blur(),!1;if(!f.length)return e.cookie&&d._cookie(e.selected,e.cookie),d.element.queue("tabs",function(){n(b,g)}),d.load(d.anchors.index(this)),this.blur(),!1}e.cookie&&d._cookie(e.selected,e.cookie);if(g.length)f.length&&d.element.queue("tabs",function(){o(b,f)}),d.element.queue("tabs",function(){n(b,g)}),d.load(d.anchors.index(this));else throw"jQuery UI Tabs: Mismatching fragment identifier.";a.browser.msie&&this.blur()}),this.anchors.bind("click.tabs",function(){return!1})},_getIndex:function(a){return typeof a=="string"&&(a=this.anchors.index(this.anchors.filter("[href$='"+a+"']"))),a},destroy:function(){var b=this.options;return this.abort(),this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs"),this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"),this.anchors.each(function(){var b=a.data(this,"href.tabs");b&&(this.href=b);var c=a(this).unbind(".tabs");a.each(["href","load","cache"],function(a,b){c.removeData(b+".tabs")})}),this.lis.unbind(".tabs").add(this.panels).each(function(){a.data(this,"destroy.tabs")?a(this).remove():a(this).removeClass(["ui-state-default","ui-corner-top","ui-tabs-selected","ui-state-active","ui-state-hover","ui-state-focus","ui-state-disabled","ui-tabs-panel","ui-widget-content","ui-corner-bottom","ui-tabs-hide"].join(" "))}),b.cookie&&this._cookie(null,b.cookie),this},add:function(c,d,e){e===b&&(e=this.anchors.length);var f=this,g=this.options,h=a(g.tabTemplate.replace(/#\{href\}/g,c).replace(/#\{label\}/g,d)),i=c.indexOf("#")?this._tabId(a("a",h)[0]):c.replace("#","");h.addClass("ui-state-default ui-corner-top").data("destroy.tabs",!0);var j=f.element.find("#"+i);return j.length||(j=a(g.panelTemplate).attr("id",i).data("destroy.tabs",!0)),j.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide"),e>=this.lis.length?(h.appendTo(this.list),j.appendTo(this.list[0].parentNode)):(h.insertBefore(this.lis[e]),j.insertBefore(this.panels[e])),g.disabled=a.map(g.disabled,function(a,b){return a>=e?++a:a}),this._tabify(),this.anchors.length==1&&(g.selected=0,h.addClass("ui-tabs-selected ui-state-active"),j.removeClass("ui-tabs-hide"),this.element.queue("tabs",function(){f._trigger("show",null,f._ui(f.anchors[0],f.panels[0]))}),this.load(0)),this._trigger("add",null,this._ui(this.anchors[e],this.panels[e])),this},remove:function(b){b=this._getIndex(b);var c=this.options,d=this.lis.eq(b).remove(),e=this.panels.eq(b).remove();return d.hasClass("ui-tabs-selected")&&this.anchors.length>1&&this.select(b+(b+1=b?--a:a}),this._tabify(),this._trigger("remove",null,this._ui(d.find("a")[0],e[0])),this},enable:function(b){b=this._getIndex(b);var c=this.options;if(a.inArray(b,c.disabled)==-1)return;return this.lis.eq(b).removeClass("ui-state-disabled"),c.disabled=a.grep(c.disabled,function(a,c){return a!=b}),this._trigger("enable",null,this._ui(this.anchors[b],this.panels[b])),this},disable:function(a){a=this._getIndex(a);var b=this,c=this.options;return a!=c.selected&&(this.lis.eq(a).addClass("ui-state-disabled"),c.disabled.push(a),c.disabled.sort(),this._trigger("disable",null,this._ui(this.anchors[a],this.panels[a]))),this},select:function(a){a=this._getIndex(a);if(a==-1)if(this.options.collapsible&&this.options.selected!=-1)a=this.options.selected;else return this;return this.anchors.eq(a).trigger(this.options.event+".tabs"),this},load:function(b){b=this._getIndex(b);var c=this,d=this.options,e=this.anchors.eq(b)[0],f=a.data(e,"load.tabs");this.abort();if(!f||this.element.queue("tabs").length!==0&&a.data(e,"cache.tabs")){this.element.dequeue("tabs");return}this.lis.eq(b).addClass("ui-state-processing");if(d.spinner){var g=a("span",e);g.data("label.tabs",g.html()).html(d.spinner)}return this.xhr=a.ajax(a.extend({},d.ajaxOptions,{url:f,success:function(f,g){c.element.find(c._sanitizeSelector(e.hash)).html(f),c._cleanup(),d.cache&&a.data(e,"cache.tabs",!0),c._trigger("load",null,c._ui(c.anchors[b],c.panels[b]));try{d.ajaxOptions.success(f,g)}catch(h){}},error:function(a,f,g){c._cleanup(),c._trigger("load",null,c._ui(c.anchors[b],c.panels[b]));try{d.ajaxOptions.error(a,f,b,e)}catch(g){}}})),c.element.dequeue("tabs"),this},abort:function(){return this.element.queue([]),this.panels.stop(!1,!0),this.element.queue("tabs",this.element.queue("tabs").splice(-2,2)),this.xhr&&(this.xhr.abort(),delete this.xhr),this._cleanup(),this},url:function(a,b){return this.anchors.eq(a).removeData("cache.tabs").data("load.tabs",b),this},length:function(){return this.anchors.length}}),a.extend(a.ui.tabs,{version:"1.8.19"}),a.extend(a.ui.tabs.prototype,{rotation:null,rotate:function(a,b){var c=this,d=this.options,e=c._rotate||(c._rotate=function(b){clearTimeout(c.rotation),c.rotation=setTimeout(function(){var a=d.selected;c.select(++a'))}function bindHover(a){var b="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return a.bind("mouseout",function(a){var c=$(a.target).closest(b);if(!c.length)return;c.removeClass("ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover")}).bind("mouseover",function(c){var d=$(c.target).closest(b);if($.datepicker._isDisabledDatepicker(instActive.inline?a.parent()[0]:instActive.input[0])||!d.length)return;d.parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),d.addClass("ui-state-hover"),d.hasClass("ui-datepicker-prev")&&d.addClass("ui-datepicker-prev-hover"),d.hasClass("ui-datepicker-next")&&d.addClass("ui-datepicker-next-hover")})}function extendRemove(a,b){$.extend(a,b);for(var c in b)if(b[c]==null||b[c]==undefined)a[c]=b[c];return a}function isArray(a){return a&&($.browser.safari&&typeof a=="object"&&a.length||a.constructor&&a.constructor.toString().match(/\Array\(\)/))}$.extend($.ui,{datepicker:{version:"1.8.19"}});var PROP_NAME="datepicker",dpuuid=(new Date).getTime(),instActive;$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",maxRows:4,log:function(){this.debug&&console.log.apply("",arguments)},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(a){return extendRemove(this._defaults,a||{}),this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var nodeName=target.nodeName.toLowerCase(),inline=nodeName=="div"||nodeName=="span";target.id||(this.uuid+=1,target.id="dp"+this.uuid);var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{}),nodeName=="input"?this._connectDatepicker(target,inst):inline&&this._inlineDatepicker(target,inst)},_newInst:function(a,b){var c=a[0].id.replace(/([^A-Za-z0-9_-])/g,"\\\\$1");return{id:c,input:a,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:b,dpDiv:b?bindHover($('
    ')):this.dpDiv}},_connectDatepicker:function(a,b){var c=$(a);b.append=$([]),b.trigger=$([]);if(c.hasClass(this.markerClassName))return;this._attachments(c,b),c.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(a,c,d){b.settings[c]=d}).bind("getData.datepicker",function(a,c){return this._get(b,c)}),this._autoSize(b),$.data(a,PROP_NAME,b),b.settings.disabled&&this._disableDatepicker(a)},_attachments:function(a,b){var c=this._get(b,"appendText"),d=this._get(b,"isRTL");b.append&&b.append.remove(),c&&(b.append=$(''+c+""),a[d?"before":"after"](b.append)),a.unbind("focus",this._showDatepicker),b.trigger&&b.trigger.remove();var e=this._get(b,"showOn");(e=="focus"||e=="both")&&a.focus(this._showDatepicker);if(e=="button"||e=="both"){var f=this._get(b,"buttonText"),g=this._get(b,"buttonImage");b.trigger=$(this._get(b,"buttonImageOnly")?$("").addClass(this._triggerClass).attr({src:g,alt:f,title:f}):$('').addClass(this._triggerClass).html(g==""?f:$("").attr({src:g,alt:f,title:f}))),a[d?"before":"after"](b.trigger),b.trigger.click(function(){return $.datepicker._datepickerShowing&&$.datepicker._lastInput==a[0]?$.datepicker._hideDatepicker():$.datepicker._datepickerShowing&&$.datepicker._lastInput!=a[0]?($.datepicker._hideDatepicker(),$.datepicker._showDatepicker(a[0])):$.datepicker._showDatepicker(a[0]),!1})}},_autoSize:function(a){if(this._get(a,"autoSize")&&!a.inline){var b=new Date(2009,11,20),c=this._get(a,"dateFormat");if(c.match(/[DM]/)){var d=function(a){var b=0,c=0;for(var d=0;db&&(b=a[d].length,c=d);return c};b.setMonth(d(this._get(a,c.match(/MM/)?"monthNames":"monthNamesShort"))),b.setDate(d(this._get(a,c.match(/DD/)?"dayNames":"dayNamesShort"))+20-b.getDay())}a.input.attr("size",this._formatDate(a,b).length)}},_inlineDatepicker:function(a,b){var c=$(a);if(c.hasClass(this.markerClassName))return;c.addClass(this.markerClassName).append(b.dpDiv).bind("setData.datepicker",function(a,c,d){b.settings[c]=d}).bind("getData.datepicker",function(a,c){return this._get(b,c)}),$.data(a,PROP_NAME,b),this._setDate(b,this._getDefaultDate(b),!0),this._updateDatepicker(b),this._updateAlternate(b),b.settings.disabled&&this._disableDatepicker(a),b.dpDiv.css("display","block")},_dialogDatepicker:function(a,b,c,d,e){var f=this._dialogInst;if(!f){this.uuid+=1;var g="dp"+this.uuid;this._dialogInput=$(''),this._dialogInput.keydown(this._doKeyDown),$("body").append(this._dialogInput),f=this._dialogInst=this._newInst(this._dialogInput,!1),f.settings={},$.data(this._dialogInput[0],PROP_NAME,f)}extendRemove(f.settings,d||{}),b=b&&b.constructor==Date?this._formatDate(f,b):b,this._dialogInput.val(b),this._pos=e?e.length?e:[e.pageX,e.pageY]:null;if(!this._pos){var h=document.documentElement.clientWidth,i=document.documentElement.clientHeight,j=document.documentElement.scrollLeft||document.body.scrollLeft,k=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[h/2-100+j,i/2-150+k]}return this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),f.settings.onSelect=c,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),$.blockUI&&$.blockUI(this.dpDiv),$.data(this._dialogInput[0],PROP_NAME,f),this},_destroyDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!b.hasClass(this.markerClassName))return;var d=a.nodeName.toLowerCase();$.removeData(a,PROP_NAME),d=="input"?(c.append.remove(),c.trigger.remove(),b.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):(d=="div"||d=="span")&&b.removeClass(this.markerClassName).empty()},_enableDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!b.hasClass(this.markerClassName))return;var d=a.nodeName.toLowerCase();if(d=="input")a.disabled=!1,c.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""});else if(d=="div"||d=="span"){var e=b.children("."+this._inlineClass);e.children().removeClass("ui-state-disabled"),e.find("select.ui-datepicker-month, select.ui-datepicker-year").removeAttr("disabled")}this._disabledInputs=$.map(this._disabledInputs,function(b){return b==a?null:b})},_disableDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!b.hasClass(this.markerClassName))return;var d=a.nodeName.toLowerCase();if(d=="input")a.disabled=!0,c.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"});else if(d=="div"||d=="span"){var e=b.children("."+this._inlineClass);e.children().addClass("ui-state-disabled"),e.find("select.ui-datepicker-month, select.ui-datepicker-year").attr("disabled","disabled")}this._disabledInputs=$.map(this._disabledInputs,function(b){return b==a?null:b}),this._disabledInputs[this._disabledInputs.length]=a},_isDisabledDatepicker:function(a){if(!a)return!1;for(var b=0;b-1}},_doKeyUp:function(a){var b=$.datepicker._getInst(a.target);if(b.input.val()!=b.lastVal)try{var c=$.datepicker.parseDate($.datepicker._get(b,"dateFormat"),b.input?b.input.val():null,$.datepicker._getFormatConfig(b));c&&($.datepicker._setDateFromField(b),$.datepicker._updateAlternate(b),$.datepicker._updateDatepicker(b))}catch(d){$.datepicker.log(d)}return!0},_showDatepicker:function(a){a=a.target||a,a.nodeName.toLowerCase()!="input"&&(a=$("input",a.parentNode)[0]);if($.datepicker._isDisabledDatepicker(a)||$.datepicker._lastInput==a)return;var b=$.datepicker._getInst(a);$.datepicker._curInst&&$.datepicker._curInst!=b&&($.datepicker._curInst.dpDiv.stop(!0,!0),b&&$.datepicker._datepickerShowing&&$.datepicker._hideDatepicker($.datepicker._curInst.input[0]));var c=$.datepicker._get(b,"beforeShow"),d=c?c.apply(a,[a,b]):{};if(d===!1)return;extendRemove(b.settings,d),b.lastVal=null,$.datepicker._lastInput=a,$.datepicker._setDateFromField(b),$.datepicker._inDialog&&(a.value=""),$.datepicker._pos||($.datepicker._pos=$.datepicker._findPos(a),$.datepicker._pos[1]+=a.offsetHeight);var e=!1;$(a).parents().each(function(){return e|=$(this).css("position")=="fixed",!e}),e&&$.browser.opera&&($.datepicker._pos[0]-=document.documentElement.scrollLeft,$.datepicker._pos[1]-=document.documentElement.scrollTop);var f={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null,b.dpDiv.empty(),b.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),$.datepicker._updateDatepicker(b),f=$.datepicker._checkOffset(b,f,e),b.dpDiv.css({position:$.datepicker._inDialog&&$.blockUI?"static":e?"fixed":"absolute",display:"none",left:f.left+"px",top:f.top+"px"});if(!b.inline){var g=$.datepicker._get(b,"showAnim"),h=$.datepicker._get(b,"duration"),i=function(){var a=b.dpDiv.find("iframe.ui-datepicker-cover");if(!!a.length){var c=$.datepicker._getBorders(b.dpDiv);a.css({left:-c[0],top:-c[1],width:b.dpDiv.outerWidth(),height:b.dpDiv.outerHeight()})}};b.dpDiv.zIndex($(a).zIndex()+1),$.datepicker._datepickerShowing=!0,$.effects&&$.effects[g]?b.dpDiv.show(g,$.datepicker._get(b,"showOptions"),h,i):b.dpDiv[g||"show"](g?h:null,i),(!g||!h)&&i(),b.input.is(":visible")&&!b.input.is(":disabled")&&b.input.focus(),$.datepicker._curInst=b}},_updateDatepicker:function(a){var b=this;b.maxRows=4;var c=$.datepicker._getBorders(a.dpDiv);instActive=a,a.dpDiv.empty().append(this._generateHTML(a));var d=a.dpDiv.find("iframe.ui-datepicker-cover");!d.length||d.css({left:-c[0],top:-c[1],width:a.dpDiv.outerWidth(),height:a.dpDiv.outerHeight()}),a.dpDiv.find("."+this._dayOverClass+" a").mouseover();var e=this._getNumberOfMonths(a),f=e[1],g=17;a.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),f>1&&a.dpDiv.addClass("ui-datepicker-multi-"+f).css("width",g*f+"em"),a.dpDiv[(e[0]!=1||e[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi"),a.dpDiv[(this._get(a,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),a==$.datepicker._curInst&&$.datepicker._datepickerShowing&&a.input&&a.input.is(":visible")&&!a.input.is(":disabled")&&a.input[0]!=document.activeElement&&a.input.focus();if(a.yearshtml){var h=a.yearshtml;setTimeout(function(){h===a.yearshtml&&a.yearshtml&&a.dpDiv.find("select.ui-datepicker-year:first").replaceWith(a.yearshtml),h=a.yearshtml=null},0)}},_getBorders:function(a){var b=function(a){return{thin:1,medium:2,thick:3}[a]||a};return[parseFloat(b(a.css("border-left-width"))),parseFloat(b(a.css("border-top-width")))]},_checkOffset:function(a,b,c){var d=a.dpDiv.outerWidth(),e=a.dpDiv.outerHeight(),f=a.input?a.input.outerWidth():0,g=a.input?a.input.outerHeight():0,h=document.documentElement.clientWidth+$(document).scrollLeft(),i=document.documentElement.clientHeight+$(document).scrollTop();return b.left-=this._get(a,"isRTL")?d-f:0,b.left-=c&&b.left==a.input.offset().left?$(document).scrollLeft():0,b.top-=c&&b.top==a.input.offset().top+g?$(document).scrollTop():0,b.left-=Math.min(b.left,b.left+d>h&&h>d?Math.abs(b.left+d-h):0),b.top-=Math.min(b.top,b.top+e>i&&i>e?Math.abs(e+g):0),b},_findPos:function(a){var b=this._getInst(a),c=this._get(b,"isRTL");while(a&&(a.type=="hidden"||a.nodeType!=1||$.expr.filters.hidden(a)))a=a[c?"previousSibling":"nextSibling"];var d=$(a).offset();return[d.left,d.top]},_hideDatepicker:function(a){var b=this._curInst;if(!b||a&&b!=$.data(a,PROP_NAME))return;if(this._datepickerShowing){var c=this._get(b,"showAnim"),d=this._get(b,"duration"),e=function(){$.datepicker._tidyDialog(b)};$.effects&&$.effects[c]?b.dpDiv.hide(c,$.datepicker._get(b,"showOptions"),d,e):b.dpDiv[c=="slideDown"?"slideUp":c=="fadeIn"?"fadeOut":"hide"](c?d:null,e),c||e(),this._datepickerShowing=!1;var f=this._get(b,"onClose");f&&f.apply(b.input?b.input[0]:null,[b.input?b.input.val():"",b]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),$.blockUI&&($.unblockUI(),$("body").append(this.dpDiv))),this._inDialog=!1}},_tidyDialog:function(a){a.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(a){if(!$.datepicker._curInst)return;var b=$(a.target),c=$.datepicker._getInst(b[0]);(b[0].id!=$.datepicker._mainDivId&&b.parents("#"+$.datepicker._mainDivId).length==0&&!b.hasClass($.datepicker.markerClassName)&&!b.closest("."+$.datepicker._triggerClass).length&&$.datepicker._datepickerShowing&&(!$.datepicker._inDialog||!$.blockUI)||b.hasClass($.datepicker.markerClassName)&&$.datepicker._curInst!=c)&&$.datepicker._hideDatepicker()},_adjustDate:function(a,b,c){var d=$(a),e=this._getInst(d[0]);if(this._isDisabledDatepicker(d[0]))return;this._adjustInstDate(e,b+(c=="M"?this._get(e,"showCurrentAtPos"):0),c),this._updateDatepicker(e)},_gotoToday:function(a){var b=$(a),c=this._getInst(b[0]);if(this._get(c,"gotoCurrent")&&c.currentDay)c.selectedDay=c.currentDay,c.drawMonth=c.selectedMonth=c.currentMonth,c.drawYear=c.selectedYear=c.currentYear;else{var d=new Date;c.selectedDay=d.getDate(),c.drawMonth=c.selectedMonth=d.getMonth(),c.drawYear=c.selectedYear=d.getFullYear()}this._notifyChange(c),this._adjustDate(b)},_selectMonthYear:function(a,b,c){var d=$(a),e=this._getInst(d[0]);e["selected"+(c=="M"?"Month":"Year")]=e["draw"+(c=="M"?"Month":"Year")]=parseInt(b.options[b.selectedIndex].value,10),this._notifyChange(e),this._adjustDate(d)},_selectDay:function(a,b,c,d){var e=$(a);if($(d).hasClass(this._unselectableClass)||this._isDisabledDatepicker(e[0]))return;var f=this._getInst(e[0]);f.selectedDay=f.currentDay=$("a",d).html(),f.selectedMonth=f.currentMonth=b,f.selectedYear=f.currentYear=c,this._selectDate(a,this._formatDate(f,f.currentDay,f.currentMonth,f.currentYear))},_clearDate:function(a){var b=$(a),c=this._getInst(b[0]);this._selectDate(b,"")},_selectDate:function(a,b){var c=$(a),d=this._getInst(c[0]);b=b!=null?b:this._formatDate(d),d.input&&d.input.val(b),this._updateAlternate(d);var e=this._get(d,"onSelect");e?e.apply(d.input?d.input[0]:null,[b,d]):d.input&&d.input.trigger("change"),d.inline?this._updateDatepicker(d):(this._hideDatepicker(),this._lastInput=d.input[0],typeof d.input[0]!="object"&&d.input.focus(),this._lastInput=null)},_updateAlternate:function(a){var b=this._get(a,"altField");if(b){var c=this._get(a,"altFormat")||this._get(a,"dateFormat"),d=this._getDate(a),e=this.formatDate(c,d,this._getFormatConfig(a));$(b).each(function(){$(this).val(e)})}},noWeekends:function(a){var b=a.getDay();return[b>0&&b<6,""]},iso8601Week:function(a){var b=new Date(a.getTime());b.setDate(b.getDate()+4-(b.getDay()||7));var c=b.getTime();return b.setMonth(0),b.setDate(1),Math.floor(Math.round((c-b)/864e5)/7)+1},parseDate:function(a,b,c){if(a==null||b==null)throw"Invalid arguments";b=typeof b=="object"?b.toString():b+"";if(b=="")return null;var d=(c?c.shortYearCutoff:null)||this._defaults.shortYearCutoff;d=typeof d!="string"?d:(new Date).getFullYear()%100+parseInt(d,10);var e=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,f=(c?c.dayNames:null)||this._defaults.dayNames,g=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,h=(c?c.monthNames:null)||this._defaults.monthNames,i=-1,j=-1,k=-1,l=-1,m=!1,n=function(b){var c=s+1-1){j=1,k=l;do{var u=this._getDaysInMonth(i,j-1);if(k<=u)break;j++,k-=u}while(!0)}var t=this._daylightSavingAdjust(new Date(i,j-1,k));if(t.getFullYear()!=i||t.getMonth()+1!=j||t.getDate()!=k)throw"Invalid date";return t},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*24*60*60*1e7,formatDate:function(a,b,c){if(!b)return"";var d=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,e=(c?c.dayNames:null)||this._defaults.dayNames,f=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,g=(c?c.monthNames:null)||this._defaults.monthNames,h=function(b){var c=m+112?a.getHours()+2:0),a):null},_setDate:function(a,b,c){var d=!b,e=a.selectedMonth,f=a.selectedYear,g=this._restrictMinMax(a,this._determineDate(a,b,new Date));a.selectedDay=a.currentDay=g.getDate(),a.drawMonth=a.selectedMonth=a.currentMonth=g.getMonth(),a.drawYear=a.selectedYear=a.currentYear=g.getFullYear(),(e!=a.selectedMonth||f!=a.selectedYear)&&!c&&this._notifyChange(a),this._adjustInstDate(a),a.input&&a.input.val(d?"":this._formatDate(a))},_getDate:function(a){var b=!a.currentYear||a.input&&a.input.val()==""?null:this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return b},_generateHTML:function(a){var b=new Date;b=this._daylightSavingAdjust(new Date(b.getFullYear(),b.getMonth(),b.getDate()));var c=this._get(a,"isRTL"),d=this._get(a,"showButtonPanel"),e=this._get(a,"hideIfNoPrevNext"),f=this._get(a,"navigationAsDateFormat"),g=this._getNumberOfMonths(a),h=this._get(a,"showCurrentAtPos"),i=this._get(a,"stepMonths"),j=g[0]!=1||g[1]!=1,k=this._daylightSavingAdjust(a.currentDay?new Date(a.currentYear,a.currentMonth,a.currentDay):new Date(9999,9,9)),l=this._getMinMaxDate(a,"min"),m=this._getMinMaxDate(a,"max"),n=a.drawMonth-h,o=a.drawYear;n<0&&(n+=12,o--);if(m){var p=this._daylightSavingAdjust(new Date(m.getFullYear(),m.getMonth()-g[0]*g[1]+1,m.getDate()));p=l&&pp)n--,n<0&&(n=11,o--)}a.drawMonth=n,a.drawYear=o;var q=this._get(a,"prevText");q=f?this.formatDate(q,this._daylightSavingAdjust(new Date(o,n-i,1)),this._getFormatConfig(a)):q;var r=this._canAdjustMonth(a,-1,o,n)?''+q+"":e?"":''+q+"",s=this._get(a,"nextText");s=f?this.formatDate(s,this._daylightSavingAdjust(new Date(o,n+i,1)),this._getFormatConfig(a)):s;var t=this._canAdjustMonth(a,1,o,n)?''+s+"":e?"":''+s+"",u=this._get(a,"currentText"),v=this._get(a,"gotoCurrent")&&a.currentDay?k:b;u=f?this.formatDate(u,v,this._getFormatConfig(a)):u;var w=a.inline?"":'",x=d?'
    '+(c?w:"")+(this._isInRange(a,v)?'":"")+(c?"":w)+"
    ":"",y=parseInt(this._get(a,"firstDay"),10);y=isNaN(y)?0:y;var z=this._get(a,"showWeek"),A=this._get(a,"dayNames"),B=this._get(a,"dayNamesShort"),C=this._get(a,"dayNamesMin"),D=this._get(a,"monthNames"),E=this._get(a,"monthNamesShort"),F=this._get(a,"beforeShowDay"),G=this._get(a,"showOtherMonths"),H=this._get(a,"selectOtherMonths"),I=this._get(a,"calculateWeek")||this.iso8601Week,J=this._getDefaultDate(a),K="";for(var L=0;L1)switch(N){case 0:Q+=" ui-datepicker-group-first",P=" ui-corner-"+(c?"right":"left");break;case g[1]-1:Q+=" ui-datepicker-group-last",P=" ui-corner-"+(c?"left":"right");break;default:Q+=" ui-datepicker-group-middle",P=""}Q+='">'}Q+='
    '+(/all|left/.test(P)&&L==0?c?t:r:"")+(/all|right/.test(P)&&L==0?c?r:t:"")+this._generateMonthYearHeader(a,n,o,l,m,L>0||N>0,D,E)+'
    '+"";var R=z?'":"";for(var S=0;S<7;S++){var T=(S+y)%7;R+="=5?' class="ui-datepicker-week-end"':"")+">"+''+C[T]+""}Q+=R+"";var U=this._getDaysInMonth(o,n);o==a.selectedYear&&n==a.selectedMonth&&(a.selectedDay=Math.min(a.selectedDay,U));var V=(this._getFirstDayOfMonth(o,n)-y+7)%7,W=Math.ceil((V+U)/7),X=j?this.maxRows>W?this.maxRows:W:W;this.maxRows=X;var Y=this._daylightSavingAdjust(new Date(o,n,1-V));for(var Z=0;Z";var _=z?'":"";for(var S=0;S<7;S++){var ba=F?F.apply(a.input?a.input[0]:null,[Y]):[!0,""],bb=Y.getMonth()!=n,bc=bb&&!H||!ba[0]||l&&Ym;_+='",Y.setDate(Y.getDate()+1),Y=this._daylightSavingAdjust(Y)}Q+=_+""}n++,n>11&&(n=0,o++),Q+="
    '+this._get(a,"weekHeader")+"
    '+this._get(a,"calculateWeek")(Y)+""+(bb&&!G?" ":bc?''+Y.getDate()+"":''+Y.getDate()+"")+"
    "+(j?"
    "+(g[0]>0&&N==g[1]-1?'
    ':""):""),M+=Q}K+=M}return K+=x+($.browser.msie&&parseInt($.browser.version,10)<7&&!a.inline?'':""),a._keyEvent=!1,K},_generateMonthYearHeader:function(a,b,c,d,e,f,g,h){var i=this._get(a,"changeMonth"),j=this._get(a,"changeYear"),k=this._get(a,"showMonthAfterYear"),l='
    ',m="";if(f||!i)m+=''+g[b]+"";else{var n=d&&d.getFullYear()==c,o=e&&e.getFullYear()==c;m+='"}k||(l+=m+(f||!i||!j?" ":""));if(!a.yearshtml){a.yearshtml="";if(f||!j)l+=''+c+"";else{var q=this._get(a,"yearRange").split(":"),r=(new Date).getFullYear(),s=function(a){var b=a.match(/c[+-].*/)?c+parseInt(a.substring(1),10):a.match(/[+-].*/)?r+parseInt(a,10):parseInt(a,10);return isNaN(b)?r:b},t=s(q[0]),u=Math.max(t,s(q[1]||""));t=d?Math.max(t,d.getFullYear()):t,u=e?Math.min(u,e.getFullYear()):u,a.yearshtml+='",l+=a.yearshtml,a.yearshtml=null}}return l+=this._get(a,"yearSuffix"),k&&(l+=(f||!i||!j?" ":"")+m),l+="
    ",l},_adjustInstDate:function(a,b,c){var d=a.drawYear+(c=="Y"?b:0),e=a.drawMonth+(c=="M"?b:0),f=Math.min(a.selectedDay,this._getDaysInMonth(d,e))+(c=="D"?b:0),g=this._restrictMinMax(a,this._daylightSavingAdjust(new Date(d,e,f)));a.selectedDay=g.getDate(),a.drawMonth=a.selectedMonth=g.getMonth(),a.drawYear=a.selectedYear=g.getFullYear(),(c=="M"||c=="Y")&&this._notifyChange(a)},_restrictMinMax:function(a,b){var c=this._getMinMaxDate(a,"min"),d=this._getMinMaxDate(a,"max"),e=c&&bd?d:e,e},_notifyChange:function(a){var b=this._get(a,"onChangeMonthYear");b&&b.apply(a.input?a.input[0]:null,[a.selectedYear,a.selectedMonth+1,a])},_getNumberOfMonths:function(a){var b=this._get(a,"numberOfMonths");return b==null?[1,1]:typeof b=="number"?[1,b]:b},_getMinMaxDate:function(a,b){return this._determineDate(a,this._get(a,b+"Date"),null)},_getDaysInMonth:function(a,b){return 32-this._daylightSavingAdjust(new Date(a,b,32)).getDate()},_getFirstDayOfMonth:function(a,b){return(new Date(a,b,1)).getDay()},_canAdjustMonth:function(a,b,c,d){var e=this._getNumberOfMonths(a),f=this._daylightSavingAdjust(new Date(c,d+(b<0?b:e[0]*e[1]),1));return b<0&&f.setDate(this._getDaysInMonth(f.getFullYear(),f.getMonth())),this._isInRange(a,f)},_isInRange:function(a,b){var c=this._getMinMaxDate(a,"min"),d=this._getMinMaxDate(a,"max");return(!c||b.getTime()>=c.getTime())&&(!d||b.getTime()<=d.getTime())},_getFormatConfig:function(a){var b=this._get(a,"shortYearCutoff");return b=typeof b!="string"?b:(new Date).getFullYear()%100+parseInt(b,10),{shortYearCutoff:b,dayNamesShort:this._get(a,"dayNamesShort"),dayNames:this._get(a,"dayNames"),monthNamesShort:this._get(a,"monthNamesShort"),monthNames:this._get(a,"monthNames")}},_formatDate:function(a,b,c,d){b||(a.currentDay=a.selectedDay,a.currentMonth=a.selectedMonth,a.currentYear=a.selectedYear);var e=b?typeof b=="object"?b:this._daylightSavingAdjust(new Date(d,c,b)):this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return this.formatDate(this._get(a,"dateFormat"),e,this._getFormatConfig(a))}}),$.fn.datepicker=function(a){if(!this.length)return this;$.datepicker.initialized||($(document).mousedown($.datepicker._checkExternalClick).find("body").append($.datepicker.dpDiv),$.datepicker.initialized=!0);var b=Array.prototype.slice.call(arguments,1);return typeof a!="string"||a!="isDisabled"&&a!="getDate"&&a!="widget"?a=="option"&&arguments.length==2&&typeof arguments[1]=="string"?$.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this[0]].concat(b)):this.each(function(){typeof a=="string"?$.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this].concat(b)):$.datepicker._attachDatepicker(this,a)}):$.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this[0]].concat(b))},$.datepicker=new Datepicker,$.datepicker.initialized=!1,$.datepicker.uuid=(new Date).getTime(),$.datepicker.version="@VERSION",window["DP_jQuery_"+dpuuid]=$})(jQuery);/*! jQuery UI - v1.8.19 - 2012-04-16 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.progressbar.js +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ +(function(a,b){a.widget("ui.progressbar",{options:{value:0,max:100},min:0,_create:function(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min,"aria-valuemax":this.options.max,"aria-valuenow":this._value()}),this.valueDiv=a("
    ").appendTo(this.element),this.oldValue=this._value(),this._refreshValue()},destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.valueDiv.remove(),a.Widget.prototype.destroy.apply(this,arguments)},value:function(a){return a===b?this._value():(this._setOption("value",a),this)},_setOption:function(b,c){b==="value"&&(this.options.value=c,this._refreshValue(),this._value()===this.options.max&&this._trigger("complete")),a.Widget.prototype._setOption.apply(this,arguments)},_value:function(){var a=this.options.value;return typeof a!="number"&&(a=0),Math.min(this.options.max,Math.max(this.min,a))},_percentage:function(){return 100*this._value()/this.options.max},_refreshValue:function(){var a=this.value(),b=this._percentage();this.oldValue!==a&&(this.oldValue=a,this._trigger("change")),this.valueDiv.toggle(a>this.min).toggleClass("ui-corner-right",a===this.options.max).width(b.toFixed(0)+"%"),this.element.attr("aria-valuenow",a)}}),a.extend(a.ui.progressbar,{version:"1.8.19"})})(jQuery);/*! jQuery UI - v1.8.19 - 2012-04-16 +* https://github.com/jquery/jquery-ui +* Includes: jquery.effects.core.js +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ +jQuery.effects||function(a,b){function c(b){var c;return b&&b.constructor==Array&&b.length==3?b:(c=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(b))?[parseInt(c[1],10),parseInt(c[2],10),parseInt(c[3],10)]:(c=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(b))?[parseFloat(c[1])*2.55,parseFloat(c[2])*2.55,parseFloat(c[3])*2.55]:(c=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(b))?[parseInt(c[1],16),parseInt(c[2],16),parseInt(c[3],16)]:(c=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(b))?[parseInt(c[1]+c[1],16),parseInt(c[2]+c[2],16),parseInt(c[3]+c[3],16)]:(c=/rgba\(0, 0, 0, 0\)/.exec(b))?e.transparent:e[a.trim(b).toLowerCase()]}function d(b,d){var e;do{e=a.curCSS(b,d);if(e!=""&&e!="transparent"||a.nodeName(b,"body"))break;d="backgroundColor"}while(b=b.parentNode);return c(e)}function h(){var a=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle,b={},c,d;if(a&&a.length&&a[0]&&a[a[0]]){var e=a.length;while(e--)c=a[e],typeof a[c]=="string"&&(d=c.replace(/\-(\w)/g,function(a,b){return b.toUpperCase()}),b[d]=a[c])}else for(c in a)typeof a[c]=="string"&&(b[c]=a[c]);return b}function i(b){var c,d;for(c in b)d=b[c],(d==null||a.isFunction(d)||c in g||/scrollbar/.test(c)||!/color/i.test(c)&&isNaN(parseFloat(d)))&&delete b[c];return b}function j(a,b){var c={_:0},d;for(d in b)a[d]!=b[d]&&(c[d]=b[d]);return c}function k(b,c,d,e){typeof b=="object"&&(e=c,d=null,c=b,b=c.effect),a.isFunction(c)&&(e=c,d=null,c={});if(typeof c=="number"||a.fx.speeds[c])e=d,d=c,c={};return a.isFunction(d)&&(e=d,d=null),c=c||{},d=d||c.duration,d=a.fx.off?0:typeof d=="number"?d:d in a.fx.speeds?a.fx.speeds[d]:a.fx.speeds._default,e=e||c.complete,[b,c,d,e]}function l(b){return!b||typeof b=="number"||a.fx.speeds[b]?!0:typeof b=="string"&&!a.effects[b]?!0:!1}a.effects={},a.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","borderColor","color","outlineColor"],function(b,e){a.fx.step[e]=function(a){a.colorInit||(a.start=d(a.elem,e),a.end=c(a.end),a.colorInit=!0),a.elem.style[e]="rgb("+Math.max(Math.min(parseInt(a.pos*(a.end[0]-a.start[0])+a.start[0],10),255),0)+","+Math.max(Math.min(parseInt(a.pos*(a.end[1]-a.start[1])+a.start[1],10),255),0)+","+Math.max(Math.min(parseInt(a.pos*(a.end[2]-a.start[2])+a.start[2],10),255),0)+")"}});var e={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]},f=["add","remove","toggle"],g={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};a.effects.animateClass=function(b,c,d,e){return a.isFunction(d)&&(e=d,d=null),this.queue(function(){var g=a(this),k=g.attr("style")||" ",l=i(h.call(this)),m,n=g.attr("class")||"";a.each(f,function(a,c){b[c]&&g[c+"Class"](b[c])}),m=i(h.call(this)),g.attr("class",n),g.animate(j(l,m),{queue:!1,duration:c,easing:d,complete:function(){a.each(f,function(a,c){b[c]&&g[c+"Class"](b[c])}),typeof g.attr("style")=="object"?(g.attr("style").cssText="",g.attr("style").cssText=k):g.attr("style",k),e&&e.apply(this,arguments),a.dequeue(this)}})})},a.fn.extend({_addClass:a.fn.addClass,addClass:function(b,c,d,e){return c?a.effects.animateClass.apply(this,[{add:b},c,d,e]):this._addClass(b)},_removeClass:a.fn.removeClass,removeClass:function(b,c,d,e){return c?a.effects.animateClass.apply(this,[{remove:b},c,d,e]):this._removeClass(b)},_toggleClass:a.fn.toggleClass,toggleClass:function(c,d,e,f,g){return typeof d=="boolean"||d===b?e?a.effects.animateClass.apply(this,[d?{add:c}:{remove:c},e,f,g]):this._toggleClass(c,d):a.effects.animateClass.apply(this,[{toggle:c},d,e,f])},switchClass:function(b,c,d,e,f){return a.effects.animateClass.apply(this,[{add:c,remove:b},d,e,f])}}),a.extend(a.effects,{version:"1.8.19",save:function(a,b){for(var c=0;c
    ").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),e=document.activeElement;return b.wrap(d),(b[0]===e||a.contains(b[0],e))&&a(e).focus(),d=b.parent(),b.css("position")=="static"?(d.css({position:"relative"}),b.css({position:"relative"})):(a.extend(c,{position:b.css("position"),zIndex:b.css("z-index")}),a.each(["top","left","bottom","right"],function(a,d){c[d]=b.css(d),isNaN(parseInt(c[d],10))&&(c[d]="auto")}),b.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),d.css(c).show()},removeWrapper:function(b){var c,d=document.activeElement;return b.parent().is(".ui-effects-wrapper")?(c=b.parent().replaceWith(b),(b[0]===d||a.contains(b[0],d))&&a(d).focus(),c):b},setTransition:function(b,c,d,e){return e=e||{},a.each(c,function(a,c){var f=b.cssUnit(c);f[0]>0&&(e[c]=f[0]*d+f[1])}),e}}),a.fn.extend({effect:function(b,c,d,e){var f=k.apply(this,arguments),g={options:f[1],duration:f[2],callback:f[3]},h=g.options.mode,i=a.effects[b];return a.fx.off||!i?h?this[h](g.duration,g.callback):this.each(function(){g.callback&&g.callback.call(this)}):i.call(this,g)},_show:a.fn.show,show:function(a){if(l(a))return this._show.apply(this,arguments);var b=k.apply(this,arguments);return b[1].mode="show",this.effect.apply(this,b)},_hide:a.fn.hide,hide:function(a){if(l(a))return this._hide.apply(this,arguments);var b=k.apply(this,arguments);return b[1].mode="hide",this.effect.apply(this,b)},__toggle:a.fn.toggle,toggle:function(b){if(l(b)||typeof b=="boolean"||a.isFunction(b))return this.__toggle.apply(this,arguments);var c=k.apply(this,arguments);return c[1].mode="toggle",this.effect.apply(this,c)},cssUnit:function(b){var c=this.css(b),d=[];return a.each(["em","px","%","pt"],function(a,b){c.indexOf(b)>0&&(d=[parseFloat(c),b])}),d}}),a.easing.jswing=a.easing.swing,a.extend(a.easing,{def:"easeOutQuad",swing:function(b,c,d,e,f){return a.easing[a.easing.def](b,c,d,e,f)},easeInQuad:function(a,b,c,d,e){return d*(b/=e)*b+c},easeOutQuad:function(a,b,c,d,e){return-d*(b/=e)*(b-2)+c},easeInOutQuad:function(a,b,c,d,e){return(b/=e/2)<1?d/2*b*b+c:-d/2*(--b*(b-2)-1)+c},easeInCubic:function(a,b,c,d,e){return d*(b/=e)*b*b+c},easeOutCubic:function(a,b,c,d,e){return d*((b=b/e-1)*b*b+1)+c},easeInOutCubic:function(a,b,c,d,e){return(b/=e/2)<1?d/2*b*b*b+c:d/2*((b-=2)*b*b+2)+c},easeInQuart:function(a,b,c,d,e){return d*(b/=e)*b*b*b+c},easeOutQuart:function(a,b,c,d,e){return-d*((b=b/e-1)*b*b*b-1)+c},easeInOutQuart:function(a,b,c,d,e){return(b/=e/2)<1?d/2*b*b*b*b+c:-d/2*((b-=2)*b*b*b-2)+c},easeInQuint:function(a,b,c,d,e){return d*(b/=e)*b*b*b*b+c},easeOutQuint:function(a,b,c,d,e){return d*((b=b/e-1)*b*b*b*b+1)+c},easeInOutQuint:function(a,b,c,d,e){return(b/=e/2)<1?d/2*b*b*b*b*b+c:d/2*((b-=2)*b*b*b*b+2)+c},easeInSine:function(a,b,c,d,e){return-d*Math.cos(b/e*(Math.PI/2))+d+c},easeOutSine:function(a,b,c,d,e){return d*Math.sin(b/e*(Math.PI/2))+c},easeInOutSine:function(a,b,c,d,e){return-d/2*(Math.cos(Math.PI*b/e)-1)+c},easeInExpo:function(a,b,c,d,e){return b==0?c:d*Math.pow(2,10*(b/e-1))+c},easeOutExpo:function(a,b,c,d,e){return b==e?c+d:d*(-Math.pow(2,-10*b/e)+1)+c},easeInOutExpo:function(a,b,c,d,e){return b==0?c:b==e?c+d:(b/=e/2)<1?d/2*Math.pow(2,10*(b-1))+c:d/2*(-Math.pow(2,-10*--b)+2)+c},easeInCirc:function(a,b,c,d,e){return-d*(Math.sqrt(1-(b/=e)*b)-1)+c},easeOutCirc:function(a,b,c,d,e){return d*Math.sqrt(1-(b=b/e-1)*b)+c},easeInOutCirc:function(a,b,c,d,e){return(b/=e/2)<1?-d/2*(Math.sqrt(1-b*b)-1)+c:d/2*(Math.sqrt(1-(b-=2)*b)+1)+c},easeInElastic:function(a,b,c,d,e){var f=1.70158,g=0,h=d;if(b==0)return c;if((b/=e)==1)return c+d;g||(g=e*.3);if(h").css({position:"absolute",visibility:"visible",left:-j*(g/d),top:-i*(h/c)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:g/d,height:h/c,left:f.left+j*(g/d)+(b.options.mode=="show"?(j-Math.floor(d/2))*(g/d):0),top:f.top+i*(h/c)+(b.options.mode=="show"?(i-Math.floor(c/2))*(h/c):0),opacity:b.options.mode=="show"?0:1}).animate({left:f.left+j*(g/d)+(b.options.mode=="show"?0:(j-Math.floor(d/2))*(g/d)),top:f.top+i*(h/c)+(b.options.mode=="show"?0:(i-Math.floor(c/2))*(h/c)),opacity:b.options.mode=="show"?1:0},b.duration||500);setTimeout(function(){b.options.mode=="show"?e.css({visibility:"visible"}):e.css({visibility:"visible"}).hide(),b.callback&&b.callback.apply(e[0]),e.dequeue(),a("div.ui-effects-explode").remove()},b.duration||500)})}})(jQuery);/*! jQuery UI - v1.8.19 - 2012-04-16 +* https://github.com/jquery/jquery-ui +* Includes: jquery.effects.fade.js +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ +(function(a,b){a.effects.fade=function(b){return this.queue(function(){var c=a(this),d=a.effects.setMode(c,b.options.mode||"hide");c.animate({opacity:d},{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}})(jQuery);/*! jQuery UI - v1.8.19 - 2012-04-16 +* https://github.com/jquery/jquery-ui +* Includes: jquery.effects.fold.js +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ +(function(a,b){a.effects.fold=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"hide"),f=b.options.size||15,g=!!b.options.horizFirst,h=b.duration?b.duration/2:a.fx.speeds._default/2;a.effects.save(c,d),c.show();var i=a.effects.createWrapper(c).css({overflow:"hidden"}),j=e=="show"!=g,k=j?["width","height"]:["height","width"],l=j?[i.width(),i.height()]:[i.height(),i.width()],m=/([0-9]+)%/.exec(f);m&&(f=parseInt(m[1],10)/100*l[e=="hide"?0:1]),e=="show"&&i.css(g?{height:0,width:f}:{height:f,width:0});var n={},p={};n[k[0]]=e=="show"?l[0]:f,p[k[1]]=e=="show"?l[1]:0,i.animate(n,h,b.options.easing).animate(p,h,b.options.easing,function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()})})}})(jQuery);/*! jQuery UI - v1.8.19 - 2012-04-16 +* https://github.com/jquery/jquery-ui +* Includes: jquery.effects.highlight.js +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ +(function(a,b){a.effects.highlight=function(b){return this.queue(function(){var c=a(this),d=["backgroundImage","backgroundColor","opacity"],e=a.effects.setMode(c,b.options.mode||"show"),f={backgroundColor:c.css("backgroundColor")};e=="hide"&&(f.opacity=0),a.effects.save(c,d),c.show().css({backgroundImage:"none",backgroundColor:b.options.color||"#ffff99"}).animate(f,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){e=="hide"&&c.hide(),a.effects.restore(c,d),e=="show"&&!a.support.opacity&&this.style.removeAttribute("filter"),b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}})(jQuery);/*! jQuery UI - v1.8.19 - 2012-04-16 +* https://github.com/jquery/jquery-ui +* Includes: jquery.effects.pulsate.js +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ +(function(a,b){a.effects.pulsate=function(b){return this.queue(function(){var c=a(this),d=a.effects.setMode(c,b.options.mode||"show"),e=(b.options.times||5)*2-1,f=b.duration?b.duration/2:a.fx.speeds._default/2,g=c.is(":visible"),h=0;g||(c.css("opacity",0).show(),h=1),(d=="hide"&&g||d=="show"&&!g)&&e--;for(var i=0;i').appendTo(document.body).addClass(b.options.className).css({top:g.top,left:g.left,height:c.innerHeight(),width:c.innerWidth(),position:"absolute"}).animate(f,b.duration,b.options.easing,function(){h.remove(),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()})})}})(jQuery); \ No newline at end of file From 5575db5718f938d61a8cd264ba65d87fda58210d Mon Sep 17 00:00:00 2001 From: rembo10 Date: Mon, 25 Jun 2012 15:58:19 +0530 Subject: [PATCH 37/52] Added spokenword/audiobook categories to nzb search providers --- headphones/searcher.py | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/headphones/searcher.py b/headphones/searcher.py index d0c5530e..92e8f739 100644 --- a/headphones/searcher.py +++ b/headphones/searcher.py @@ -115,9 +115,9 @@ def searchNZB(albumid=None, new=False, losslessOnly=False): myDB = db.DBConnection() if albumid: - results = myDB.select('SELECT ArtistName, AlbumTitle, AlbumID, ReleaseDate from albums WHERE AlbumID=?', [albumid]) + results = myDB.select('SELECT ArtistName, AlbumTitle, AlbumID, ReleaseDate, Type from albums WHERE AlbumID=?', [albumid]) else: - results = myDB.select('SELECT ArtistName, AlbumTitle, AlbumID, ReleaseDate from albums WHERE Status="Wanted" OR Status="Wanted Lossless"') + results = myDB.select('SELECT ArtistName, AlbumTitle, AlbumID, ReleaseDate, Type from albums WHERE Status="Wanted" OR Status="Wanted Lossless"') new = True for albums in results: @@ -162,6 +162,11 @@ def searchNZB(albumid=None, new=False, losslessOnly=False): else: categories = "22" + # Search Audiobooks + if albums['Type'] == "Other": + categories = "49" + logger.info("Album type is audiobook/spokenword. Using audiobook category") + # For some reason NZBMatrix is erroring out/timing out when the term starts with a "The" right now # so we'll strip it out for the time being. This may get fixed on their end, it may not, but # hopefully this will fix it for now. If you notice anything else it gets stuck on, please post it @@ -212,7 +217,11 @@ def searchNZB(albumid=None, new=False, losslessOnly=False): elif headphones.PREFERRED_QUALITY: categories = "3040,3010" else: - categories = "3010" + categories = "3010" + + if albums['Type'] == 'Other': + categories = "3030" + logger.info("Album type is audiobook/spokenword. Using audiobook category") params = { "t": "search", "apikey": headphones.NEWZNAB_APIKEY, @@ -259,7 +268,11 @@ def searchNZB(albumid=None, new=False, losslessOnly=False): elif headphones.PREFERRED_QUALITY: categories = "3040,3010" else: - categories = "3010" + categories = "3010" + + if albums['Type'] == 'Other': + categories = "3030" + logger.info("Album type is audiobook/spokenword. Using audiobook category") params = { "t": "search", "apikey": headphones.NZBSORG_HASH, @@ -312,6 +325,11 @@ def searchNZB(albumid=None, new=False, losslessOnly=False): categories = "7" #music format = "8" #mp3 + if albums['Type'] == 'Other': + categories = "13" + format = "16" + logger.info("Album type is audiobook/spokenword. Using audiobook category") + params = { "fpn": "p", 'u_nfo_posts_only': 0, From 77a887c09b896cba662bfc3c654883a5dc750767 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Mon, 25 Jun 2012 18:47:21 +0530 Subject: [PATCH 38/52] New function: getImageLinks(ArtistID/AlbumID). Just queries last fm to grab the artwork/thumbnail links without saving them to the cache. Useful for search results, etc --- headphones/cache.py | 89 ++++++++++++++++++++++++++++++++++++++++++ headphones/webserve.py | 10 +++++ 2 files changed, 99 insertions(+) diff --git a/headphones/cache.py b/headphones/cache.py index fa3e1083..32ca9d62 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -194,6 +194,88 @@ class Cache(object): else: info_dict = { 'Summary' : db_info['Summary'], 'Content' : db_info['Content'] } return info_dict + + def get_image_links(self, ArtistID=None, AlbumID=None): + ''' + Here we're just going to open up the last.fm url, grab the image links and return them + Won't save any image urls, or save the artwork in the cache. Useful for search results, etc. + ''' + if ArtistID: + + self.id_type = 'artist' + + params = { "method": "artist.getInfo", + "api_key": lastfm_apikey, + "mbid": ArtistID, + "format": "json" + } + + url = "http://ws.audioscrobbler.com/2.0/?" + urllib.urlencode(params) + logger.debug('Retrieving artist information from: ' + url) + + try: + result = urllib2.urlopen(url, timeout=20).read() + except: + logger.warn('Could not open url: ' + url) + return + + if result: + + try: + data = simplejson.JSONDecoder().decode(result) + except: + logger.warn('Could not parse data from url: ' + url) + return + + try: + image_url = data['artist']['image'][-1]['#text'] + except KeyError: + logger.debug('No artist image found on url: ' + url) + image_url = None + + thumb_url = self._get_thumb_url(data) + if not thumb_url: + logger.debug('No artist thumbnail image found on url: ' + url) + + else: + + self.id_type = 'album' + + params = { "method": "album.getInfo", + "api_key": lastfm_apikey, + "mbid": AlbumID, + "format": "json" + } + + url = "http://ws.audioscrobbler.com/2.0/?" + urllib.urlencode(params) + logger.debug('Retrieving album information from: ' + url) + + try: + result = urllib2.urlopen(url, timeout=20).read() + except: + logger.warn('Could not open url: ' + url) + return + + if result: + + try: + data = simplejson.JSONDecoder().decode(result) + except: + logger.warn('Could not parse data from url: ' + url) + return + + try: + image_url = data['artist']['image'][-1]['#text'] + except KeyError: + logger.debug('No artist image found on url: ' + url) + image_url = None + + thumb_url = self._get_thumb_url(data) + if not thumb_url: + logger.debug('No artist thumbnail image found on url: ' + url) + + image_dict = {'artwork' : image_url, 'thumbnail' : thumb_url } + return image_dict def _update_cache(self): ''' @@ -429,3 +511,10 @@ def getInfo(ArtistID=None, AlbumID=None): info_dict = c.get_info_from_cache(ArtistID, AlbumID) return info_dict + +def getImageLinks(ArtistID=None, AlbumID=None): + + c = Cache() + image_links = c.get_image_links(ArtistID, AlbumID) + + return image_links diff --git a/headphones/webserve.py b/headphones/webserve.py index 4fabb3fd..e2589ba1 100644 --- a/headphones/webserve.py +++ b/headphones/webserve.py @@ -616,3 +616,13 @@ class WebInterface(object): return cache.getThumb(ArtistID, AlbumID) getThumb.exposed = True + + # If you just want to get the last.fm image links for an album, make sure to pass a releaseid and not a releasegroupid + def getImageLinks(self, ArtistID=None, AlbumID=None): + + from headphones import cache + image_dict = cache.getImageLinks(ArtistID, AlbumID) + + return simplejson.dumps(image_dict) + + getImageLinks.exposed = True From fa1a4afdb396c6101540c03e47a248f54dadd60c Mon Sep 17 00:00:00 2001 From: rembo10 Date: Mon, 25 Jun 2012 22:44:20 +0530 Subject: [PATCH 39/52] Initial changes to the default template to use the cache --- data/interfaces/default/artist.html | 39 ++++++- data/interfaces/default/base.html | 7 +- data/interfaces/default/index.html | 5 +- data/interfaces/default/js/script.js | 157 ++++++++++----------------- 4 files changed, 94 insertions(+), 114 deletions(-) diff --git a/data/interfaces/default/artist.html b/data/interfaces/default/artist.html index e234475b..c385683b 100644 --- a/data/interfaces/default/artist.html +++ b/data/interfaces/default/artist.html @@ -27,7 +27,7 @@ <%def name="body()">
    - ${artist['ArtistName']} + ${artist['ArtistName']}

    %if artist['Status'] == 'Loading': @@ -109,7 +109,7 @@ %> - + ${album['AlbumTitle']} ${album['ReleaseDate']} ${album['Type']} @@ -148,11 +148,41 @@ - - - + + + ${next.javascriptIncludes()} diff --git a/data/interfaces/default/index.html b/data/interfaces/default/index.html index 218f2303..16a97a30 100644 --- a/data/interfaces/default/index.html +++ b/data/interfaces/default/index.html @@ -74,11 +74,10 @@ function getArtistArt() { $("table#artist_table tr td#name").each(function(){ var id = $(this).children('a').attr('title'); - var artist = $(this).children('a').text(); var image = $(this).parent().find("td#albumart img"); if ( !image.hasClass('done') ) { image.addClass('done'); - getArtistInfo(artist,image,1,id); + getThumb(image,id,'artist'); } }); } @@ -114,4 +113,4 @@ }); - \ No newline at end of file + diff --git a/data/interfaces/default/js/script.js b/data/interfaces/default/js/script.js index 15b379d2..5688063a 100644 --- a/data/interfaces/default/js/script.js +++ b/data/interfaces/default/js/script.js @@ -1,110 +1,65 @@ -function getArtistInfo(name,imgElem,size,artistID) { - var apikey = "690e1ed3bc00bc91804cd8f7fe5ed6d4"; +function getThumb(imgElem,id,type) { - // Get Data by Artist ID - $.ajax({ - url: "http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&mbid="+ artistID +"&api_key="+ apikey+"&format=json", - dataType: "jsonp", - cache: true, - success: function(data){ - if ( data.artist !== undefined ) { - var imageUrl = data.artist.image[size]['#text']; - } - if (data.error) { - getArtistName(); - } else { - if ( data.artist === undefined || imageUrl == "" || imageUrl == undefined ) { - var imageLarge = "#"; - var imageUrl = "interfaces/default/images/no-cover-artist.png"; - } else { - var artist = data.artist.mbid; - var artistBio = data.artist.bio.summary; - var imageLarge = data.artist.image[4]['#text']; - var imageUrl = data.artist.image[size]['#text']; - } - var artistBio = artistBio; - var image = imgElem; - var bio = $('#artistBio'); - $(image).attr("src",imageUrl).removeAttr("width").removeAttr("height").hide().fadeIn(); - if ( bio.length > 0 ) $(bio).append(artistBio); - $(image).wrap(''); - } - } - }); - // If not found get by Name - function getArtistName() { - $.ajax({ - url: "http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&artist="+ name +"&api_key="+ apikey+"&format=json", - dataType: "jsonp", - success: function(data){ - if ( data.artist !== undefined ) { - var imageUrl = data.artist.image[size]['#text']; - } - if ( data.artist === undefined || imageUrl == "" ) { - var imageLarge = "#"; - var imageUrl = "interfaces/default/images/no-cover-artist.png"; - } else { - var artist = data.artist.name; - var artistBio = data.artist.bio.summary; - var imageLarge = data.artist.image[4]['#text']; - var imageUrl = data.artist.image[size]['#text']; - } - var artistBio = artistBio; - var image = imgElem; - var bio = $('#artistBio'); - $(image).attr("src",imageUrl).removeAttr("width").removeAttr("height").hide().fadeIn(); - if ( bio.length > 0 ) $(bio).append(artistBio); - $(image).wrap(''); - } - }); + if ( type == 'artist' ) { + var thumbURL = "getThumb?ArtistID=" + id; + } else { + var thumbURL = "getThumb?AlbumID=" + id; } + // Get Data from the cache by Artist ID + $.ajax({ + url: thumbURL, + success: function(data){ + if ( data == "" ) { + var imageUrl = "interfaces/default/images/no-cover-artist.png"; + } + else { + var imageUrl = data; + } + $(imgElem).attr("src",imageUrl).removeAttr("width").removeAttr("height").hide().fadeIn(); + $(imgElem).wrap(''); + } + }); } -function getAlbumInfo(name, album, elem,size) { - var apikey = "690e1ed3bc00bc91804cd8f7fe5ed6d4"; - var dimensions = getOriginalWidthOfImg(this); - var cover = $(elem); +function getArtwork(imgElem,id,type) { - if ( dimensions <= 1) { - // Get Data - $.ajax({ - url: "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=" + apikey + "&artist="+ name +"&album="+ album +"&format=json&callback=?", - dataType: "jsonp", - success: function(data){ - if ( data.artist !== undefined ) { - var imageUrl = data.artist.image[size]['#text']; - } - if (data.album === undefined || imageUrl == "") { - if ( elem.width() == 50 ) { - var imageUrl = "interfaces/default/images/no-cover-artist.png"; - } else { - var imageUrl = "interfaces/default/images/no-cover-art.png"; - } - } else { - var imageUrl = data.album.image[size]['#text']; - var imageLarge = data.album.image[3]['#text']; - } - $(cover).error(function(){ - if ( elem.width() == 50 ) { - var imageUrl = "interfaces/default/images/no-cover-artist.png"; - } else { - var imageUrl = "interfaces/default/images/no-cover-art.png"; - } - $(elem).css("background", "url("+ imageUrl+") center top no-repeat"); - }); - if ( imageUrl == "") { - if ( elem.width() == 50 ) { - var imageUrl = "interfaces/default/images/no-cover-artist.png"; - } else { - var imageUrl = "interfaces/default/images/no-cover-art.png"; - } - $(elem).css("background", "url("+ imageUrl+") center top no-repeat"); - } - $(elem).css("background", "url("+ imageUrl+") center top no-repeat"); - $(elem).wrap(''); - } - }); + if ( type == 'artist' ) { + var artworkURL = "getArtwork?ArtistID=" + id; + } else { + var artworkURL = "getArtwork?AlbumID=" + id; } + // Get Data from the cache by Artist ID + $.ajax({ + url: artworkURL, + success: function(data){ + if ( data == "" ) { + var imageUrl = "interfaces/default/images/no-cover-artist.png"; + } + else { + var imageUrl = data; + } + $(imgElem).attr("src",imageUrl).removeAttr("width").removeAttr("height").hide().fadeIn(); + $(imgElem).wrap(''); + } + }); +} + +function getInfo(elem,id,type) { + + if ( type == 'artist' ) { + var infoURL = "getInfo?ArtistID=" + id; + } else { + var infoURL = "getInfo?AlbumID=" + id; + } + // Get Data from the cache by Artist ID + $.ajax({ + url: infoURL, + data_type: "jsonp", + success: function(data){ + var summary = data['Summary']; + $(elem).append(summary); + } + }); } function getOriginalWidthOfImg(img_element) { From f4074f433a5b556d2c9927b6ffaaf9c7b8f1e28d Mon Sep 17 00:00:00 2001 From: rembo10 Date: Mon, 25 Jun 2012 23:50:01 +0530 Subject: [PATCH 40/52] Moved all of the ajax functions over to use the cache rather than last.fm/amazon --- data/interfaces/default/album.html | 25 ++++++++++++---- data/interfaces/default/artist.html | 2 +- data/interfaces/default/js/script.js | 28 +++++++++++++++--- data/interfaces/default/manageartists.html | 22 +++++++++----- data/interfaces/default/searchresults.html | 34 ++++++++++++---------- data/interfaces/default/upcoming.html | 21 +++++++++---- 6 files changed, 92 insertions(+), 40 deletions(-) diff --git a/data/interfaces/default/album.html b/data/interfaces/default/album.html index c76a520b..d5b1b54a 100644 --- a/data/interfaces/default/album.html +++ b/data/interfaces/default/album.html @@ -26,7 +26,7 @@
    - albumart + albumart

    ${album['AlbumTitle']}

    @@ -41,9 +41,7 @@ %>
    - %if description: -

    ${description['Summary']}

    - %endif +
    • Tracks: ${totaltracks}
    • Duration: ${albumduration}
    • @@ -128,8 +126,25 @@ <%def name="javascriptIncludes()"> - \ No newline at end of file + diff --git a/data/interfaces/default/searchresults.html b/data/interfaces/default/searchresults.html index bbf07f58..0207a223 100644 --- a/data/interfaces/default/searchresults.html +++ b/data/interfaces/default/searchresults.html @@ -26,8 +26,12 @@ else: grade = 'Z' %> - -
      + + %if type == 'album': +
      + %else: +
      + %endif %if type == 'album': ${result['title']} %endif @@ -55,20 +59,18 @@ - \ No newline at end of file + diff --git a/data/interfaces/default/upcoming.html b/data/interfaces/default/upcoming.html index 56a410d0..625e1bcd 100644 --- a/data/interfaces/default/upcoming.html +++ b/data/interfaces/default/upcoming.html @@ -40,7 +40,7 @@ %for album in wanted: - + ${album['ArtistName']} ${album['AlbumTitle']} ${album['ReleaseDate']} @@ -70,7 +70,7 @@ %for album in upcoming: - + ${album['ArtistName']} ${album['AlbumTitle']} ${album['ReleaseDate']} @@ -90,7 +90,19 @@ <%def name="javascriptIncludes()"> - \ No newline at end of file + From a8a368080615e461164e592dc7a5084d6c822ba9 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 26 Jun 2012 00:01:23 +0530 Subject: [PATCH 41/52] Moved bencode.py to the lib folder and changed the import in searcher.py --- headphones/searcher.py | 2 +- {headphones => lib}/bencode.py | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename {headphones => lib}/bencode.py (100%) diff --git a/headphones/searcher.py b/headphones/searcher.py index 01d50202..c610a236 100644 --- a/headphones/searcher.py +++ b/headphones/searcher.py @@ -26,7 +26,7 @@ import string import headphones, exceptions from headphones import logger, db, helpers, classes, sab -import bencode +import lib.bencode as bencode class NewzbinDownloader(urllib.FancyURLopener): diff --git a/headphones/bencode.py b/lib/bencode.py similarity index 100% rename from headphones/bencode.py rename to lib/bencode.py From c20094cb46ae6d808ad7add5a7ff85b2be9fa2e3 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 26 Jun 2012 09:20:56 +0530 Subject: [PATCH 42/52] Cache the ajax calls to the thumbnail urls --- data/interfaces/default/js/script.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/data/interfaces/default/js/script.js b/data/interfaces/default/js/script.js index 3f042362..3d7d61ff 100644 --- a/data/interfaces/default/js/script.js +++ b/data/interfaces/default/js/script.js @@ -8,6 +8,7 @@ function getThumb(imgElem,id,type) { // Get Data from the cache by Artist ID $.ajax({ url: thumbURL, + cache: true, success: function(data){ if ( data == "" ) { var imageUrl = "interfaces/default/images/no-cover-artist.png"; @@ -31,6 +32,7 @@ function getArtwork(imgElem,id,type) { // Get Data from the cache by Artist ID $.ajax({ url: artworkURL, + cache: true; success: function(data){ if ( data == "" ) { var imageUrl = "interfaces/default/images/no-cover-artist.png"; @@ -54,6 +56,7 @@ function getInfo(elem,id,type) { // Get Data from the cache by ID $.ajax({ url: infoURL, + cache: true, dataType: "json", success: function(data){ var summary = data.Summary; @@ -72,6 +75,7 @@ function getImageLinks(elem,id,type) { // Get Data from the cache by ID $.ajax({ url: infoURL, + cache: true, dataType: "json", success: function(data){ var thumbnail = data.thumbnail; From df9a3021b42d46892d83eaf9785d2a646f320c7a Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 26 Jun 2012 09:26:49 +0530 Subject: [PATCH 43/52] Removed unused function in script.js, fixed typo --- data/interfaces/default/js/script.js | 39 +--------------------------- 1 file changed, 1 insertion(+), 38 deletions(-) diff --git a/data/interfaces/default/js/script.js b/data/interfaces/default/js/script.js index 3d7d61ff..6f7a00de 100644 --- a/data/interfaces/default/js/script.js +++ b/data/interfaces/default/js/script.js @@ -32,7 +32,7 @@ function getArtwork(imgElem,id,type) { // Get Data from the cache by Artist ID $.ajax({ url: artworkURL, - cache: true; + cache: true, success: function(data){ if ( data == "" ) { var imageUrl = "interfaces/default/images/no-cover-artist.png"; @@ -92,43 +92,6 @@ function getOriginalWidthOfImg(img_element) { return t.width; } -function replaceEmptyAlbum(elem,name) { - var album = $(elem); - var artist = name; - var albumname; - var apikey = "690e1ed3bc00bc91804cd8f7fe5ed6d4"; - // Loop through every album art and get the albums with no cover - $(album).each(function(e){ - var dimensions = getOriginalWidthOfImg(this); - var cover = $(this); - var url; - albumname = cover.closest("tr").find("#albumname a").text(); - if ( dimensions <= 1) { - url = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=" + apikey + "&artist="+ artist +"&album="+ albumname +"&format=json&callback=?"; - var imageUrl; - $.getJSON(url, function(data, response) { - if (data.album === undefined) { - imageUrl = "interfaces/default/images/no-cover-art.png"; - } else { - imageUrl = data.album.image[3]['#text']; - imageLarge = data.album.image[4]['#text']; - // If Last.fm don't provide a cover then use standard - } - $(cover).error(function(){ - imageUrl = "interfaces/default/images/no-cover-art.png"; - $(this).hide().attr("src", imageUrl).show(); - }) - if ( imageUrl == "") { - imageUrl = "interfaces/default/images/no-cover-art.png"; - $(this).hide().attr("src", imageUrl).show(); - } - $(cover).hide().attr("src", imageUrl).show(); - $(cover).wrap(''); - }); - } - }); -} - function initHeader() { //settings var header = $("#container header"); From e26dabbeca1022bdf16fc55273050d8a29a2a600 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 26 Jun 2012 12:09:51 +0530 Subject: [PATCH 44/52] A couple syle changes to keep the artist image normally proportioned. Also fixed the fancy boxes on the artist & album pages --- data/interfaces/default/album.html | 10 ++++++---- data/interfaces/default/artist.html | 15 ++++++--------- data/interfaces/default/js/script.js | 8 ++++---- 3 files changed, 16 insertions(+), 17 deletions(-) diff --git a/data/interfaces/default/album.html b/data/interfaces/default/album.html index d5b1b54a..fd4d99fe 100644 --- a/data/interfaces/default/album.html +++ b/data/interfaces/default/album.html @@ -129,10 +129,11 @@ function getAlbumArt() { var id = "${album['AlbumID']}"; + var name = "${album['AlbumTitle']}"; var image = $("div#albumImg img#albumImg"); if ( !image.hasClass('done') ) { image.addClass('done'); - getArtwork(image,id,'album'); + getArtwork(image,id,name,'album'); } } @@ -146,6 +147,9 @@ getAlbumInfo(); getAlbumArt(); initActions(); + setTimeout(function(){ + initFancybox(); + },1000); $('#track_table').dataTable({ "aaSorting": [], @@ -154,8 +158,6 @@ "bPaginate": false }); }); - $(window).load(function(){ - initFancybox(); - }); + diff --git a/data/interfaces/default/artist.html b/data/interfaces/default/artist.html index 560b1732..71165052 100644 --- a/data/interfaces/default/artist.html +++ b/data/interfaces/default/artist.html @@ -27,7 +27,7 @@ <%def name="body()">
      - ${artist['ArtistName']} + ${artist['ArtistName']}

      %if artist['Status'] == 'Loading': @@ -109,7 +109,7 @@ %> - + ${album['AlbumTitle']} ${album['ReleaseDate']} ${album['Type']} @@ -151,10 +151,11 @@ function getArtistArt() { var id = "${artist['ArtistID']}"; - var image = $("div#artistImg img#artistImg"); + var name = "${artist['ArtistName']}"; + var image = $("div#artistImg img#artistImage"); if ( !image.hasClass('done') ) { image.addClass('done'); - getArtwork(image,id,'artist'); + getArtwork(image,id,name,'artist'); } } @@ -220,10 +221,6 @@ initActions(); initThisPage(); }); - $(window).load(function(){ - setTimeout(function(){ - initFancybox(); - },1000) - }); + diff --git a/data/interfaces/default/js/script.js b/data/interfaces/default/js/script.js index 6f7a00de..41bd06a8 100644 --- a/data/interfaces/default/js/script.js +++ b/data/interfaces/default/js/script.js @@ -17,12 +17,12 @@ function getThumb(imgElem,id,type) { var imageUrl = data; } $(imgElem).attr("src",imageUrl).hide().fadeIn(); - $(imgElem).wrap(''); + // $(imgElem).wrap(''); } }); } -function getArtwork(imgElem,id,type) { +function getArtwork(imgElem,id,name,type) { if ( type == 'artist' ) { var artworkURL = "getArtwork?ArtistID=" + id; @@ -40,8 +40,8 @@ function getArtwork(imgElem,id,type) { else { var imageUrl = data; } - $(imgElem).attr("src",imageUrl).removeAttr("width").removeAttr("height").hide().fadeIn(); - $(imgElem).wrap(''); + $(imgElem).attr("src",imageUrl).hide().fadeIn(); + $(imgElem).wrap(''); } }); } From 39d1afc0891866df20c776a24efc1d0c4531e5d9 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 26 Jun 2012 13:50:55 +0530 Subject: [PATCH 45/52] Fixed bug where marking albums as wanted on the album page resulted in it getting marked twice - and then loading the artist subhead instead of album subhead --- data/interfaces/default/js/script.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/data/interfaces/default/js/script.js b/data/interfaces/default/js/script.js index 41bd06a8..a89bb618 100644 --- a/data/interfaces/default/js/script.js +++ b/data/interfaces/default/js/script.js @@ -153,7 +153,8 @@ function initActions() { $("#subhead_menu #menu_link_scan").button({ icons: { primary: "ui-icon-search"} }); } -function refreshSubmenu(url) { +function refreshSubmenu() { + var url = $(location).attr('href'); $("#subhead_container").load(url + " #subhead_menu",function(){ initActions(); }); @@ -303,7 +304,7 @@ function doAjaxCall(url,elem,reload,form) { feedback.fadeOut(function(){ feedback.removeClass('success'); }); - if ( reload == true ) refreshSubmenu(url); + if ( reload == true ) refreshSubmenu(); if ( reload == "table") { console.log('refresh'); refreshTable(); } From 1f397857c66ee37ef5bfdb9f1fac28d677372f73 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 26 Jun 2012 14:12:31 +0530 Subject: [PATCH 46/52] Fixed bug where albums would show up under upcoming on the upcoming/wanted page after an album was marked as skipped or downloaded --- data/interfaces/default/css/data_table.css | 48 ++++++++++++++++++++++ data/interfaces/default/upcoming.html | 2 +- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/data/interfaces/default/css/data_table.css b/data/interfaces/default/css/data_table.css index 820d947e..afaf4d04 100644 --- a/data/interfaces/default/css/data_table.css +++ b/data/interfaces/default/css/data_table.css @@ -129,6 +129,54 @@ table.display td.center { text-align: center; } +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Little hack to handle the two tables on the upcoming page + */ +table.display_no_select { + margin: 20px auto; + clear: both; + border:1px solid #EEE; + width: 100%; + + /* Note Firefox 3.5 and before have a bug with border-collapse + * ( https://bugzilla.mozilla.org/show%5Fbug.cgi?id=155955 ) + * border-spacing: 0; is one possible option. Conditional-css.com is + * useful for this kind of thing + * + * Further note IE 6/7 has problems when calculating widths with border width. + * It subtracts one px relative to the other browsers from the first column, and + * adds one to the end... + * + * If you want that effect I'd suggest setting a border-top/left on th/td's and + * then filling in the gaps with other borders. + */ +} + +table.display_no_select thead th { + padding: 3px 18px 3px 10px; + background-color: white; + font-weight: bold; + font-size: 16px; +} + +table.display_no_select tfoot th { + padding: 3px 18px 3px 10px; + border-top: 1px solid black; + font-weight: bold; +} + +table.display_no_select tr.heading2 td { + border-bottom: 1px solid #aaa; +} + +table.display_no_select td { + padding: 8px 10px; + font-size: 16px; +} +table +table.display_no_select td.center { + text-align: center; +} /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * diff --git a/data/interfaces/default/upcoming.html b/data/interfaces/default/upcoming.html index 625e1bcd..bbe3e312 100644 --- a/data/interfaces/default/upcoming.html +++ b/data/interfaces/default/upcoming.html @@ -56,7 +56,7 @@

      Upcoming AlbumsUpcoming Albums

      - +
      From 05cc10df1a91ffde32bc50d21a96fd987edfc054 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 26 Jun 2012 19:02:02 +0530 Subject: [PATCH 47/52] Merge in elmarkou's changes --- data/interfaces/default/album.html | 4 +-- data/interfaces/default/artist.html | 4 +-- data/interfaces/default/css/style.css | 14 ++++---- data/interfaces/default/css/style.less | 11 ++++++ data/interfaces/default/css/style_bu.css | 1 - .../default/images/no-cover-artist.png | Bin 6937 -> 8988 bytes data/interfaces/default/index.html | 2 +- data/interfaces/default/js/script.js | 33 ++++++++++-------- data/interfaces/default/upcoming.html | 4 +-- 9 files changed, 45 insertions(+), 28 deletions(-) delete mode 100644 data/interfaces/default/css/style_bu.css diff --git a/data/interfaces/default/album.html b/data/interfaces/default/album.html index fd4d99fe..7dde799d 100644 --- a/data/interfaces/default/album.html +++ b/data/interfaces/default/album.html @@ -26,7 +26,7 @@
      - albumart +

      ${album['AlbumTitle']}

      @@ -130,7 +130,7 @@ function getAlbumArt() { var id = "${album['AlbumID']}"; var name = "${album['AlbumTitle']}"; - var image = $("div#albumImg img#albumImg"); + var image = $("div#albumImg img"); if ( !image.hasClass('done') ) { image.addClass('done'); getArtwork(image,id,name,'album'); diff --git a/data/interfaces/default/artist.html b/data/interfaces/default/artist.html index 71165052..2c1349fc 100644 --- a/data/interfaces/default/artist.html +++ b/data/interfaces/default/artist.html @@ -27,7 +27,7 @@ <%def name="body()">
      - ${artist['ArtistName']} +

      %if artist['Status'] == 'Loading': @@ -214,7 +214,7 @@ resetFilters("albums"); setTimeout(function(){ initFancybox(); - },1000); + },1500) } $(document).ready(function() { diff --git a/data/interfaces/default/css/style.css b/data/interfaces/default/css/style.css index ab6e2ac0..8bfb9acf 100644 --- a/data/interfaces/default/css/style.css +++ b/data/interfaces/default/css/style.css @@ -158,6 +158,8 @@ img.albumArt { float: left; min-height: 100%; min-width: 100%; + max-width: 300px; + max-height: 300px; position: relative; } .title { @@ -750,12 +752,6 @@ div#searchbar .mini-icon { margin-left: 6px; margin-top: 6px; } -a#vipserver { - margin-left: 100px; - color: blue; - size: 95%; - font-weight: bold; -} .configtable legend { font-size: 16px; font-weight: bold; @@ -1363,6 +1359,12 @@ div#artistheader h3 span { text-align: center; vertical-align: middle; } +#upcoming_table td#albumart img, +#wanted_table td#albumart img { + background: #FFF; + border: 1px solid #ccc; + padding: 3px; +} #upcoming_table th#albumart, #wanted_table th#albumart { min-width: 50px; diff --git a/data/interfaces/default/css/style.less b/data/interfaces/default/css/style.less index 86a91c0b..2c8c67a6 100644 --- a/data/interfaces/default/css/style.less +++ b/data/interfaces/default/css/style.less @@ -84,6 +84,8 @@ img { float: left; min-height: 100%; min-width: 100%; + max-width: 250px; + max-height: 300px; position: relative; } } @@ -1083,6 +1085,15 @@ div#albumheader .albuminfo li span, div#artistheader h3 span { text-align: center; vertical-align: middle; } +#upcoming_table, #wanted_table { + td#albumart { + img { + background: #FFF; + border: 1px solid #ccc; + padding: 3px; + } + } +} #upcoming_table th#albumart, #wanted_table th#albumart { min-width: 50px; text-align: center; diff --git a/data/interfaces/default/css/style_bu.css b/data/interfaces/default/css/style_bu.css deleted file mode 100644 index e72d2e11..00000000 --- a/data/interfaces/default/css/style_bu.css +++ /dev/null @@ -1 +0,0 @@ -html,body,div,span,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,abbr,address,cite,code,del,dfn,em,img,ins,kbd,q,samp,small,strong,sub,sup,var,b,i,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,figcaption,figure,footer,header,hgroup,menu,nav,section,summary,time,mark,audio,video{border:0;font:inherit;font-size:100%;margin:0;padding:0;vertical-align:baseline}article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}html{color:#343434;font-size:12px;line-height:1.5}body{background:#fff;color:#343434;font-family:"Helvetica Neue",Helvetica,Arial,Geneva,sans-serif;margin:0;overflow-y:scroll;padding:0}a{color:#4183c4;text-decoration:none;outline:0}a:hover{color:#8b8b8b}a.blue{color:blue}a .ui-icon{display:inline-block;position:relative;top:2px}.links a{color:#666;clear:both;display:inline-block;float:left}.links a:hover{color:#4183c4}.links a .ui-icon{float:left;margin-right:5px;margin-top:3px}h1{font-size:24px}h2{font-size:20px}h3{font-size:16px}p.center{text-align:center}hr{border:0;border-top:1px solid #ccc;display:block;height:1px;margin:1em 0;padding:0}small{font-size:85%}img.albumArt{float:left;min-height:100%;min-width:100%;position:relative}.title{margin-bottom:20px;margin-top:10px}.title h1 img{float:left;margin-right:5px}table{border-collapse:collapse;border-spacing:0}table th{background-image:-moz-linear-gradient(#fafafa,#eaeaea)!important;background-image:linear-gradient(#fafafa,#eaeaea)!important;background-image:-webkit-linear-gradient(#fafafa,#eaeaea)!important;filter:progid:dximagetransform.microsoft.gradient(startColorstr=#fafafa,endColorstr=#eaeaea)!important;-ms-filter:progid:dximagetransform.microsoft.gradient(startColorstr=#fafafa,endColorstr=#eaeaea)!important;text-shadow:1px 1px 0 #fff}table th input[type="checkbox"]{vertical-align:middle}table td{vertical-align:top}table td a{color:#666}select,input,textarea,button{font:99%}textarea{overflow:auto}input{-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px}input:invalid,textarea:invalid{-moz-box-shadow:0 0 5px #f00;-webkit-box-shadow:0 0 5px #f00;box-shadow:0 0 5px #f00;-moz-border-radius:1px;-webkit-border-radius:1px;border-radius:1px}.no-boxshadow input:invalid,.no-boxshadow textarea:invalid{background-color:#f0dddd}input[type="checkbox"]{vertical-align:bottom}label,input[type="button"],input[type="submit"],input[type="image"],button{cursor:pointer}button,input,select,textarea{margin:0}button{overflow:visible;width:auto}input,select,form .checkbox input,.configtable td#middle,#artist_table td#have,#album_table td#have{vertical-align:middle}input[type="radio"]{vertical-align:text-bottom}::-moz-selection,::selection{background:grey;color:#fff;text-shadow:none}input[type=submit],input[type=button]{-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px;background:#222 url("../images/button.png") repeat-x;border:0;border-bottom:1px solid rgba(0,0,0,0.25);color:#fff;cursor:pointer;display:inline-block;margin-right:3px;padding:4px 10px;position:relative;text-decoration:none;text-shadow:0 -1px 1px rgba(0,0,0,0.25)}form legend,form h2{font-size:16px;font-weight:bold;margin-bottom:10px}form table{width:100%}form fieldset{margin-bottom:20px}form fieldset small.heading{color:#666;display:block;font-style:italic;margin-bottom:10px;margin-top:-15px}form .row{font-family:Helvetica,Arial;margin-bottom:10px}form .row label{display:block;float:left;font-size:12px;line-height:normal;padding-top:7px;width:175px}form .row input{margin-right:5px}form .row input[type=text],form .row input[type=password]{border:1px solid #DDD;border-top:1px solid #cdcdcd;-moz-box-shadow:0 1px 0 #f1f1f1;-webkit-box-shadow:0 1px 0 #f1f1f1;box-shadow:0 1px 0 #f1f1f1;-moz-box-shadow:inset 0 1px 1px #e0e0e0;-webkit-box-shadow:inset 0 1px 1px #e0e0e0;box-shadow:inset 0 1px 1px #e0e0e0;color:#343434;font-size:14px;height:auto;line-height:normal;max-width:230px;margin-right:5px;padding:3px 5px}form .row small{color:#999;display:block;font-size:9px;line-height:12px;margin-left:175px;margin-top:3px}form .left label{float:none;line-height:normal;margin-bottom:10px;padding-top:1px;width:auto}form .left input{float:left;margin-bottom:10px}form .radio label{float:none;line-height:normal;margin-bottom:10px;padding-top:1px;width:auto}form .radio input{float:left;margin-bottom:10px}form .radio small{display:inline!important;line-height:normal!important;margin:0!important;width:auto}form .checkbox small{display:inline!important;line-height:normal!important;margin:0!important;width:auto}ul,ol{margin-left:2em}ol{list-style-type:decimal}nav ul,nav li{list-style:none;list-style-image:none;margin:0}ul#nav{float:right;margin:0;padding:0 0 0 10px;border-left:1px solid #fafafa;-moz-box-shadow:-1px 0 0 #e0e0e0;-webkit-box-shadow:-1px 0 0 #e0e0e0;box-shadow:-1px 0 0 #e0e0e0;height:58px}ul#nav li{display:block;float:left;font-size:18px;font-weight:bold;margin:8px 0 0 0;text-align:center}ul#nav li a{color:#343434;display:block;padding:7px 15px;text-shadow:1px 1px 0 #FFF;text-transform:capitalize;border:1px solid transparent;font-family:"Trebuchet MS",Helvetica,Arial,sans-serif}ul#nav li a:hover{background-image:-moz-linear-gradient(#f1f1f1,#e0e0e0)!important;background-image:linear-gradient(#f1f1f1,#e0e0e0)!important;background-image:-webkit-linear-gradient(#f1f1f1,#e0e0e0)!important;filter:progid:dximagetransform.microsoft.gradient(startColorstr=#fafafa,endColorstr=#eaeaea)!important;-ms-filter:progid:dximagetransform.microsoft.gradient(startColorstr=#fafafa,endColorstr=#eaeaea)!important;border:1px solid #ddd;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;-moz-box-shadow:0 1px 0 #fafafa;-webkit-box-shadow:0 1px 0 #fafafa;box-shadow:0 1px 0 #fafafa;-moz-box-shadow:0 1px 0 #fafafa inset;-webkit-box-shadow:0 1px 0 #fafafa inset;box-shadow:0 1px 0 #fafafa inset;-webkit-transition:color .2s ease-in;-moz-transition:color .2s ease-in;-o-transition:color .2s ease-in;transition:color .2s ease-in}ul#nav li a.config{height:28px;width:10px}ul#nav li a.config img{position:relative;top:-7px;left:-7px}ul#nav li a.log{font-size:13px;padding:10px 15px 11px}header{background-image:-moz-linear-gradient(#fafafa,#eaeaea)!important;background-image:linear-gradient(#fafafa,#eaeaea)!important;background-image:-webkit-linear-gradient(#fafafa,#eaeaea)!important;filter:progid:dximagetransform.microsoft.gradient(startColorstr=#fafafa,endColorstr=#eaeaea)!important;-ms-filter:progid:dximagetransform.microsoft.gradient(startColorstr=#fafafa,endColorstr=#eaeaea)!important;border-bottom:1px solid #cacaca;-moz-box-shadow:0 0 10px rgba(0,0,0,0.1);-webkit-box-shadow:0 0 10px rgba(0,0,0,0.1);box-shadow:0 0 10px rgba(0,0,0,0.1);height:58px;position:fixed;width:100%;z-index:999}header .wrapper{margin:0 auto;overflow:hidden;position:relative;width:960px}header #logo{float:left;margin-right:20px;position:relative;top:-3px;margin-left:10px}footer{display:table;margin:20px auto;width:960px}#main{line-height:24px;margin:0 auto;padding:75px 0 0;width:960px}.message{-moz-border-radius:10px;-webkit-border-radius:10px;border-radius:10px;background-color:#fff6a9;display:inline-block;padding:5px 10px;margin-top:10px}.message .ui-icon{float:left;margin-right:5px;position:relative;top:4px}#ajaxMsg{background-color:#fdfff2;border:1px solid #ccc;-moz-border-radius-bottomleft:10px;-moz-border-radius-bottomright:10px;-webkit-border-bottom-right-radius:10px;-webkit-border-bottom-left-radius:10px;border-bottom-left-radius:10px;border-bottom-right-radius:10px;display:none;font-size:14px;left:50%;margin-left:-125px;min-height:16px;padding:0 10px;position:fixed;text-align:center;top:-1px;width:250px;z-index:9999}#ajaxMsg .msg{font-family:"Trebuchet MS",Helvetica,Arial,sans-serif;line-height:normal;padding-left:20px}#ajaxMsg.success{background-color:#d3ffd7;padding:10px 10px 10px}#ajaxMsg.error{background-color:#ffd3d3;padding:10px 10px 10px}#ajaxMsg .ui-icon{display:inline-block;margin-left:-20px;top:2px;position:relative;margin-right:3px}#updatebar{-moz-border-radius-bottomleft:10px;-moz-border-radius-bottomright:10px;-webkit-border-bottom-right-radius:10px;-webkit-border-bottom-left-radius:10px;border-bottom-left-radius:10px;border-bottom-right-radius:10px;background-color:#fff6a9;border:1px solid #ccc;font-size:11px;left:35%;margin:0 auto;padding:1px 10px;position:absolute;text-align:center;text-transform:lowercase;top:0}#subhead .back{float:left;margin-top:-25px}#subhead #subhead_container{float:right;height:30px;list-style-type:none;width:100%;z-index:998}#subhead #subhead_container #subhead_menu{float:right;margin-top:5px;position:relative;z-index:99}#subhead #subhead_container #subhead_menu a{background-image:-moz-linear-gradient(#f4f4f4,#e7e7e7)!important;background-image:linear-gradient(#f4f4f4,#e7e7e7)!important;background-image:-webkit-linear-gradient(#f4f4f4,#e7e7e7)!important;filter:progid:dximagetransform.microsoft.gradient(startColorstr=#fafafa,endColorstr=#eaeaea)!important;-ms-filter:progid:dximagetransform.microsoft.gradient(startColorstr=#fafafa,endColorstr=#eaeaea)!important;font-family:"Helvetica Neue",Helvetica,Arial,Geneva,sans-serif;font-size:12px;font-weight:normal}#subhead #subhead_container #subhead_menu a:hover{background-image:-moz-linear-gradient(#599bdc,#3072b3)!important;background-image:linear-gradient(#599bdc,#3072b3)!important;background-image:-webkit-linear-gradient(#599bdc,#3072b3)!important;filter:progid:dximagetransform.microsoft.gradient(startColorstr=#fafafa,endColorstr=#eaeaea)!important;-ms-filter:progid:dximagetransform.microsoft.gradient(startColorstr=#fafafa,endColorstr=#eaeaea)!important;color:#FFF;border-color:#518cc6 #518cc6 #2a65a0}div#searchbar{border-left:1px solid #fafafa;-moz-box-shadow:-1px 0 0 #e0e0e0;-webkit-box-shadow:-1px 0 0 #e0e0e0;box-shadow:-1px 0 0 #e0e0e0;padding:15px 0 15px 20px;position:absolute;left:90px;top:2px}div#searchbar input[type=text]{border:1px solid #DDD;border-top:1px solid #cdcdcd;-moz-box-shadow:0 1px 0 #f1f1f1;-webkit-box-shadow:0 1px 0 #f1f1f1;box-shadow:0 1px 0 #f1f1f1;-moz-box-shadow:inset 0 1px 1px #e0e0e0;-webkit-box-shadow:inset 0 1px 1px #e0e0e0;box-shadow:inset 0 1px 1px #e0e0e0;color:#999;float:left;font-size:14px;height:auto;line-height:normal;margin-right:5px;padding:4px 5px 4px 25px;width:150px}div#searchbar .mini-icon{height:20px;width:20px;background:url("../images/icon_search.gif") left top no-repeat;position:absolute;display:block;margin-left:6px;margin-top:6px}.configtable legend{font-size:16px;font-weight:bold;margin-bottom:10px;text-shadow:1px 1px 0 #fff}.configtable tr td:last-child{border-left:1px dotted #ddd;padding-left:20px}.configtable td{padding-right:15px;width:50%}.table_wrapper{_height:302px;background-color:#FFF;clear:both;margin:30px auto 0;min-height:100px;position:relative;width:100%;zoom:1px}.manage_wrapper{_height:302px;clear:both;margin:20px auto 0;min-height:150px;padding:25px;width:88%;zoom:1px}#paddingheader{position:relative;top:-25px}#paddingheader h1{line-height:33px;width:450px}#paddingheader h1 img{float:left;margin-right:5px}div#nopaddingheader{font-size:24px;font-weight:bold;text-align:center}div#artistheader{margin-top:50px;min-height:200px}div#artistheader #artistImg{background:#fff url("../images/loader_black.gif") center no-repeat;border:5px solid #FFF;-moz-box-shadow:1px 1px 2px 0 #555;-webkit-box-shadow:1px 1px 2px 0 #555;box-shadow:1px 1px 2px 0 #555;float:left;height:200px;margin-bottom:30px;margin-right:25px;overflow:hidden;text-indent:-3000px;width:200px}div#artistheader #artistBio{font-size:16px;line-height:24px;margin-top:10px}div#artistheader h1 a{font-size:32px;margin-bottom:5px;font-family:"Trebuchet MS",Helvetica,Arial,sans-serif}div#artistheader h2 a{font-style:italic;font-weight:bold;font-family:"Trebuchet MS",Helvetica,Arial,sans-serif}#artist_table{background-color:#FFF;padding:20px;width:100%}#artist_table th#select{text-align:left}#artist_table th#select input{vertical-align:middle}#artist_table th#name{min-width:200px;text-align:left}#artist_table th#album{min-width:300px;text-align:left}#artist_table th#status,#artist_table th#albumart{min-width:50px;text-align:left}#artist_table th#have{text-align:center}#artist_table td#name{min-width:200px;text-align:left;vertical-align:middle}#artist_table td#status{min-width:50px;text-align:left;vertical-align:middle}#artist_table td#album{min-width:300px;text-align:left;vertical-align:middle}#markalbum{position:relative;top:25px;display:inline-block}#albumheader{margin-top:50px;min-height:200px}#albumheader #albumImg{background:#fff url("../images/loader_black.gif") center no-repeat;border:5px solid #FFF;-moz-box-shadow:1px 1px 2px 0 #555;-webkit-box-shadow:1px 1px 2px 0 #555;box-shadow:1px 1px 2px 0 #555;float:left;height:200px;margin-bottom:30px;margin-right:25px;overflow:hidden;text-indent:-3000px;width:200px}#albumheader p{font-size:16px;line-height:24px;margin-bottom:10px}#albumheader h1 a{display:inline-block;font-size:32px;line-height:35px;margin-bottom:3px;font-family:"Trebuchet MS",Helvetica,Arial,sans-serif}#albumheader h2 a{display:inline-block;font-style:italic;font-weight:400;margin-bottom:5px;font-family:"Trebuchet MS",Helvetica,Arial,sans-serif}#albumheader .albuminfo{margin-left:210px}#albumheader .albuminfo li{border-right:1px dotted #ccc;float:left;font-size:16px;font-weight:bold;list-style:none;margin-right:10px;padding-right:10px}#albumheader .albuminfo li:last-child{border:0}#album_table{background-color:#FFF}#album_table th#select{min-width:10px;text-align:left;vertical-align:middle}#album_table th#select input{vertical-align:middle}#album_table th#reldate{min-width:70px;text-align:center;width:175px}#album_table th#status,#album_table th#albumart{min-width:50px;text-align:left}#album_table th#status{min-width:80px;text-align:center;width:175px}#album_table th#wantlossless{min-width:80px;text-align:center;width:80px}#album_table td#albumart img{background:#FFF;border:1px solid #ccc;padding:3px}#album_table td#status a#wantlossless{white-space:nowrap}#manageheader{margin-top:45px;margin-bottom:0}#track_wrapper{font-size:16px;padding-top:20px;width:100%}#track_table th#number{min-width:10px;text-align:right}#track_table th#name{min-width:350px;text-align:center}#track_table th#location{text-align:center;width:250px}#track_table td{border-bottom:1px solid #fff}#track_table td#number{text-align:right;vertical-align:middle}#track_table td#name{font-size:15px;text-align:left;vertical-align:middle}#track_table td#location{font-size:11px;line-height:normal;text-align:center;vertical-align:middle}#history_table{background-color:#FFF;font-size:13px;width:100%}#history_table td#dateadded{font-size:14px;min-width:150px;text-align:center;vertical-align:middle}#history_table td#filename{font-size:15px;min-width:100px;text-align:center;vertical-align:middle}#history_table td#size{font-size:14px;min-width:75px;text-align:center;vertical-align:middle}#log_table{background-color:#FFF}#log_table th#timestamp{min-width:150px;text-align:left}#log_table th#level{min-width:60px;text-align:left}#log_table th#message{min-width:500px;text-align:left}#log_table td{font-size:12px;padding:2px 10px}#searchresults_table th#albumname{min-width:225px;text-align:left}#searchresults_table th#artistname{min-width:325px;text-align:center}#searchresults_table td#albumname{min-width:200px;text-align:left;vertical-align:middle}#searchresults_table td#artistname{min-width:300px;text-align:left;vertical-align:middle}#searchresults_table td#score .bar{width:100px;margin:0 auto;border:1px solid #ccc;padding:1px;background-color:#FFF}#searchresults_table td#score .bar .score{height:14px;color:#343434;color:#FFF;font-size:11px;vertical-align:middle;line-height:normal;background-image:-moz-linear-gradient(#a3e532,#90cc2a)!important;background-image:linear-gradient(#a3e532,#90cc2a)!important;background-image:-webkit-linear-gradient(#a3e532,#90cc2a)!important;filter:progid:dximagetransform.microsoft.gradient(startColorstr=#fafafa,endColorstr=#eaeaea)!important;-ms-filter:progid:dximagetransform.microsoft.gradient(startColorstr=#fafafa,endColorstr=#eaeaea)!important}.progress-container{background:#FFF;border:1px solid #ccc;float:left;height:14px;margin:2px 5px 2px 0;padding:1px;width:100px}.progress-container>div{background-image:-moz-linear-gradient(#a3e532,#90cc2a)!important;background-image:linear-gradient(#a3e532,#90cc2a)!important;background-image:-webkit-linear-gradient(#a3e532,#90cc2a)!important;filter:progid:dximagetransform.microsoft.gradient(startColorstr=#fafafa,endColorstr=#eaeaea)!important;-ms-filter:progid:dximagetransform.microsoft.gradient(startColorstr=#fafafa,endColorstr=#eaeaea)!important;height:14px}.havetracks{font-size:11px;line-height:normal;margin-left:36px;padding-bottom:3px;vertical-align:middle}#version{color:#999;font-size:10px;position:relative;z-index:999;margin:20px auto;text-align:center;width:390px}#donate{margin:20px auto;text-align:center}#toTop{background:url("../images/toTop.gif") no-repeat scroll 10px center #f7f7f7;border-radius:5px 0 0 0;bottom:0;display:none;padding:10px 10px 10px 40px;position:fixed;right:0}#shutdown{text-align:center;vertical-align:middle}#shutdown h1 img{position:relative;top:7px}.cloudtag{font-size:16px;padding-top:30px}.cloudtag #cloud{line-height:1.5em;margin:0;padding:2px;text-align:center}.cloudtag #cloud a{padding:0}.cloudtag #cloud a.tag1{font-size:.7em;font-weight:100}.cloudtag #cloud a.tag2{font-size:.8em;font-weight:200}.cloudtag #cloud a.tag3{font-size:.9em;font-weight:300}.cloudtag #cloud a.tag4{font-size:1em;font-weight:400}.cloudtag #cloud a.tag5{font-size:1.2em;font-weight:500}.cloudtag #cloud a.tag6{font-size:1.4em;font-weight:600}.cloudtag #cloud a.tag7{font-size:1.6em;font-weight:bold}.cloudtag #cloud a.tag8{font-size:1.8em;font-weight:800}.cloudtag #cloud a.tag9{font-size:2.2em;font-weight:900}.cloudtag #cloud a.tag10{font-size:2.5em;font-weight:900}.cloudtag #cloud li{display:inline}.floatright{float:right}.floatleft{float:left}.ir{background-repeat:no-repeat;direction:ltr;display:block;overflow:hidden;text-align:left;text-indent:-999em}.hidden{display:none;visibility:hidden}.visuallyhidden{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.visuallyhidden.focusable:active,.visuallyhidden.focusable:focus{clip:auto;height:auto;margin:0;overflow:visible;position:static;width:auto}.invisible{visibility:hidden}.clearfix:before,.clearfix:after{content:"\0020";display:block;height:0;overflow:hidden}.clearfix{zoom:1px}.clearfix:after{clear:both}#album_table th#albumname,#upcoming_table th#artistname,#wanted_table th#artistname{min-width:150px;text-align:center}#album_table th#type,#track_table th#duration{min-width:100px;text-align:center;width:175px}#album_table th#bitrate,#album_table th#albumformat{min-width:60px;text-align:center}#album_table td#select,#album_table td#albumart{text-align:left;vertical-align:middle}#album_table td#albumname,#album_table td#reldate,#album_table td#type,#track_table td#duration,#upcoming_table td#select,#upcoming_table td#status,#wanted_table td#select,#wanted_table td#status{text-align:center;vertical-align:middle}#album_table td#status,#album_table td#bitrate,#album_table td#albumformat,#album_table td#wantlossless{font-size:13px;text-align:center;vertical-align:middle}div#albumheader .albuminfo li span,div#artistheader h3 span{font-weight:400}#track_table th#bitrate,#track_table th#format,#upcoming_table th#type,#wanted_table th#type,#searchresults_table th#score{min-width:75px;text-align:center}#track_table td#bitrate,#track_table td#format{font-size:12px;text-align:center;vertical-align:middle}#history_table td#status,#history_table td#action{font-size:14px;text-align:center;vertical-align:middle}#upcoming_table th#albumart,#wanted_table th#albumart{min-width:50px;text-align:center}#upcoming_table th#albumname,#wanted_table th#albumname{min-width:200px;text-align:center}#upcoming_table th#reldate,#wanted_table th#reldate{min-width:100px;text-align:center}#upcoming_table td#albumart,#wanted_table td#albumart{min-width:50px;text-align:center;vertical-align:middle}#upcoming_table td#albumname,#wanted_table td#albumname{min-width:200px;text-align:center;vertical-align:middle}#upcoming_table td#artistname,#wanted_table td#artistname{min-width:150px;text-align:center;vertical-align:middle}#upcoming_table td#reldate,#wanted_table td#reldate{min-width:100px;text-align:center;vertical-align:middle}#upcoming_table td#type,#wanted_table td#type,#searchresults_table td#score{min-width:75px;text-align:center;vertical-align:middle}table tr td#status a{color:#4183c4}.ie7 input[type="checkbox"]{vertical-align:baseline}.ie7 img{-ms-interpolation-mode:bicubic}.ie7 legend{margin-left:-7px} \ No newline at end of file diff --git a/data/interfaces/default/images/no-cover-artist.png b/data/interfaces/default/images/no-cover-artist.png index 2a716ae2361286f021400ca2321c4800ecdbab17..40fe7903abb853dbcc15a3ab648b434e7902aa9d 100644 GIT binary patch delta 6329 zcmWle2{csiAI3+PBwI|jtl5SpO9@k=#y$v>eH%-5vNb}uvPM)CvWwqP){v21gk(2q z(qxaxPO@+R_dn;(oik_7J@38m`~5!8=XobXFG(eB@t1T_ z>uT|_>I$bMg{zsKlLr)`KJqBv^F$w4Lvy@)i8X0_lC(A#4CUhEWpdVa5)uYn~D*?s-%=&L0(!(tWt!ntH^3g^}A=9J?Wkecs0^f zQBjfXO(7_P|3>uOJUu&F!Vca$bTE8d!vEXeo=Mgg{1neAX-`r7 zyQkt`&kwt041e(8f&F*`{?GDq^sF+uEOnaIJ3HX>tY0)*MCxUaiZTkdH*{mIiKKMx zTCGQDXj7pDvdEkAO!--%RhoFf0I!q2NOT1I$Zf_dDTtux)F&4GZDwN^4M9-g+}Bid zFGA3lE@+$?s9rhl^D{Y_P%2d<4_Tf&%uP$sjck3SUdTWKPV!j$eGUv9a+; z#@l_k_9Q4*+lEXpLYGUOULLE_k$4$mZcg@65p30AT);I3 zuHc-Ysvmo93fH|Xx$bi_2j1{e;fQ}96BF|+K0f~7Gy}siDOprIFnnv&{NaUIk>mbT zMyX;w;?Y4cMiDwNhWz{*42gaM*}{Bn(=F1(=Qe}!fq{Y7B1R<*b3+@7i(QxB#0g$6 zC|T5gWAx{N7)Q_7YOf>cbObwEH2KSs_H#k#Xw9c(Z$5W;c$k^`>n@zYm82ywfU+US zEH$jFu;o&X(TvJe;pkgU3thE`gO8WgO-;>BM;oZYQ`rH%)j#$&sg1HWAJ-?ZWb{1` zT=}^br!5%#J5QgaawbA)8&ZQQQ|%K)l6Azu@16(SD+jXb>gqeMdgqK3_(q*Aw;|X^ zqIU<;`(wpY>+sYm6cr5mY!-Q4h)#?#diPRqwYJnKiaK(582ayMXA*L-x1Tz8%?sNe zU!l~U)F68UHa9m1RTc;0BB$_KB!?je`G{8m^;I^)qdcX(32Y%J%q&({lo6 z{O49P>D0dhv=LZ7MP?`JbVuBza>&0wX%iE6S2Oe%8!9&U_JTbqis&~lgqjUVp!Sa` zxUV^xx2LlYgy~u(XXpvv)C~Eu3J^qOuXu;tw}%tK)YBvqN#N1;a=Z~n4QABn4MPz8 z#W;fZSL!B@54;qigSPDzif3j~eJUpAPs5$|X*n@nbiIvMxmlD04_J(9WRyGug~)yG zMgHJfB@3qPc>}u9d`(6@tm)`0u^!d%!`*%V`ope?=0_Q`$|rTn@o9FGTcN6aNmnon z19cN2OKY2Zheu&yVRy8(<4Eh8pB?4FF*$k9QcHnP6H?%dDL@>fBV~raUQ4Tfk)KMp zqh+>1`)*bl44xtuoE>oRt3Dvir+MqUEUbw=NlRVNaykX(JCJ;*7&KhVqp7yXt&Kq& zGf_aIELuYAWeOTgN*H6%_KCOCoZT{GEs(@N76>>R0gpuX>M;;5h+om8;h<~B+aeMi ze?Y{Qe>*#sY7hPl4W5l@f4T4=6Nwk%QW2TBgMhdH`}c2O?Qoi{Qb;9ez45u~zT3@I z%vh~e(huV0FK3mh`LEC<1)UVS0Tgq`I=8-5v&4+jTRUoQ3{vZOwfzx8A`w+qFt;8g1myut3-Jo%j`8Ik$Nw5M~! zPL6gUjMS(GlBvRSe@+%UqiM{}6sA5_TwJ`dMaG@%*0mn3cor5G3V4z$%9%JJr^Lrt zCX&Lij^+!oGq+=1DT;I!4HXAwBVXz7E69BK%2UpGwsZ@K} zBb=-gA-$b?wQB! z(XCIoTo819o0;J^sWwiRA{fz9ce~mGvun9vIxY%lT}bs!xiR8M9A#jZ11-3#22-q`Vx`2jMBPZ7wMHu5cbO>0Ww7_VN zUC+^JPK&m&y2KL7W?c{=mxOJ|ghcrc1q1)><+0NP*{DqjXF$@YzX~rUFQHY0IXO9- zeOiyUOY3c93J?kI6h(bfbdftE6$1+DNvER`ypv5Lp&&v&Hb`ZagtH|dZ5Fxj*HfyI z7HN1Ep^xV_eeg}D?B1&15$%g}{+1K1(1{*}=zZhY*q9}3DkS%G;Kqz5?3Q$D0t+*< z*Uj)lX!oHqwW0t~S=4WpMxUl5#?BPu3k)q+ zRQuU7lItnx`zl-VT*VSc7mr76rqHs+x)YT6IDnNx3|o|*xh2N&*x3?1=ogoo*Liu` zV9jQgRT1Ti(}Lv@AJ4T6d7U@7opR%uy4vA-N3oLEkM*8s0ykW2$@F(k&u8c}05=)m z-RKtbp|uarrSip2%jz3hlkpA|ML-Q0LW;29aTS<0T47y|qM{->HMQrVs%#KRAu8rP z_8q)^di`2P2XRHyUZHjD0?iv#n(x3FSUS67wo35d;{fV_cgXsu)6eJpQF5Bb_B>ku z+GEaURoK+0q=>y+Zjj+#WTE~l&IEO^sq(gDF$;K|W%LIfc~BndGPdo%e~Te|BTGvD z{Q1+CdChZ(M2ed0O;;x=Kt>qQQ}grlzI%V2ZCXNk$Go@*SY6)~@uMS`NHN%RtcO|Y z=;xuKA@#d=?_Rpxo9WndkAqvrCTI%C(xm$fIzbIvWmb-Oy1=!GByL>jIdHeI(8zC1J=KXU7Zm@GO&@{M_)WFZ zBtCnFHiqDNx>$@glhouq>uvV#?rw8dHnz#;;7ynJp{ha`0MX@SXZOK;vnf(0_%O9lM~}jF)}@GsJbVX`)CzaW?929>T$l-s-H?qhCQ2L}w8G&!M!!Rc0My9P|yWFkoAS)5QfkFD)w z^m$_xQ-v^(Qw>t^7ZlUzo*4^Zrm(zxg)ep2rR2-}+Cqb1xrwyE2kg5KV?=@bFL-2v z4zTU>*hOQb87^a->8L%f4Hu-|DhV@zIlxke{?TUU4W3zT-m!ZS7-;A8Scw)rgji21 zeOkBv@GELZnR*S) zC>i}e_IhU&=KWidw9D490|R%|mVPC~4jqmu7@+b7ix-xcy?#_9rQFhPEA1)I&x-5Ka?HY$JtG!eIT!SLHPCOzX>LYuFxxyOHtj@NT?i!La7 zeW|dnyASNc6mM(pqn*K0bh$&$cX!<(^xv>H=nx>O>ju}AuL|!*As+HNSrEN=`MW>i zj{kD=EBnF%0s_Jt?{_Ag2c26|a*>}kN`Br|Rs@e5{HaX6;?xH%EiY%=)%(vWFRiXt zsIIrsa;xqAemPcERrPJHK5g_w4C=9 zE|=Uw)4+X6kjt$fzA-EHOY3(@)|ZGgE4PBK0k^8j4%qjm)mB13(WpoEUI7NeDx{it zd>roe<2}vJ_(LJHGK=ZDS!6F-F{=|KF2Cc$;J&`Te7njh`B;#9E?X1x8yhK-8n3W@ z{rzvS?{<^M05M_+GlLfyYa1-5Pen{jOeC+at_CG*0s=?SV4}QsikNZrgufv!U$&rWso|}OG&uC0m&q|0kn-L6eo`oJ+%qTB zL2DYp>Eks{0mrFE9z<54CJxloX)Z3V7UPCBAiuC% z3Vh|Si-H}&O%%5t{_Q;gJ#$`j*p@7=#7W!IkImHkZQmnMwhJKMivscwJ>3i~w74x5@bL>qpB(Z_4qjo_i7roij>1aFhud{~u{#f!i)L; zPc4pBug%~DnaEq41wI7hDw9+x9=rE6q7z`d1I*zIv7R-fr`fWvO7mNv{=k-w=9fsr zK6X0FSCn{!?W~SN`V!Dfb#xjvJ1SmBpYfCJ!*SD}psWwr0OFDAZB`dTnk!;DrZcI* z3U8Nx^|-IJdA&D`64wP_7>?oO1StF@UQVOXcrqtCh2YL-Vyand6*H@B1dpL^?!A~* zz6XfMsj_8%QSD)1-~i(UY%1%!g)l4_lmMx+dHbiDEz}%RyR^G8JGr4^$TsrrMsw}r zdcw00h@$Apr^#6i={UF{-3HVisQcvcQ(HL znMWOL2Y^f5?Cpg!^(Bh!prfsmW`M$K1d_X+eyz+;=y)@)j&5pkwA8N3qVH>U_BCcF zTg9xEYHw>}cqe0|ujF`sDkH@vigELNl*L8wuhoh7t}MtPk#5|wcFZ)d_r{>X@NKq1 zmCe4#_pVr;VK~rq^7m=l=&F6I5SdF22C{!)tO4&?WmR60otbIn&J+8YC*X_-S+4Vj zJ4-*yi#Fl^T7&%5x?VpyUR+=IwMd)ml?AS%)&gq(M3OJbOf$s0N2PH14|aCr&(abn zW9uMK4dA57qpeCP>`A}?#3;f_cy;)@M#b z{ZOrK)S7^vr6V2!l>tHm1GKF_qRXJ*gAMI}y z+l4F;j-KD#{&7%zC&%B1;MaaXwalc{RNufL=hsKS+4{W0-;xwIf$RT9dR|KAeSENh zHSe%tK|dk!7&b1jR`}8nZoZvWPI0z$fZYQbG-fSq?Gf(g$>F9@wrbcuPC`=B6-3B3 z$mjdY{j(7;cAJ#{5|F)lr!tUPB7oS%s>o}|9^C1~a z=xX^>KeF&480>cBO*Y_{T&t1Ll`B{N`cxwa^-?~p3vKrrZ=~_PbZVGY<^&rZIdTS@ z+0K@E%Rg&NT|+|lSEr|^8(m#p%|{`RTIan`RlCyBi$(6z6-yY$w~^SdyiU0Vh>9Zj zT78MTEO8wH0Mban$0bQDK3)HJ$;hcm^DSs)b~ zT?caq|L!&Y9W}?53xWt$i}W-_axHy8mNuJ6i!W}4z;8v%O9bbdOGZN`g~M*9qz_H* znU-BYe(!HB$pWYH_WJ*ng&k~*r1$R8-hJrNSO}wwNph@uf_`HUb||OOZ{)J?6fc04 zt_@PjMWpvu0lfaEaQR%4mL({otRhS1xQ_D_Vs9L)fHc?@t}~Gq$r}^}p0;~8=SKZe cD-CSvn`eu21*_aI@NWc6SM!cW1=>FHf2(Y9c>n+a delta 4261 zcmWldc|26zAIB$zP{tCHFe+KgGGv*D8kBttQ8BiZEqlg#?Sx2V&sL*GH4;W-Z8B5O zJj@__wk(s#5`)P2o!@=k<-c>!J>Spg{rR3-dZkDc@xa>h>QNqX9vBRE)Wq1(7ChDd ze{pkyyQF?vT^*u~2Z9@#7+$u+j=jDS<#%iFDXVu@Z=o0Kg{q@u3F-DeZk#YwBmM-?Ip#sni~x`9^6<(vIx#JJm*FuRg>2k>3&`M30+X$EyvjKix-0K>MqFP zClsi8%%n7RmV%WmE7A=qzjM&Z_!+5YY5pUJuwdFAvJl-tfwuSd+kM@gL)WbMjUB#bDn$Psg4Upz;@ap9l;0Y&u#G=Ed+j-s9%j& zcXxNQ%C$qhe6U!tlbU{Ux1C0s0;KXUV6t##1>ZMl`l;34jtzGOP_#rwM15H*<_LGM zwj9ni^8{pIVBk9yyZ1|1e`h-JNn&E+25&O@>vjxmO&(WPC3oI~FR$Mc!EqdIO)gBk z@@(OIcLpsyJY1^vXU!`Yb&C*4ul#}_n(*J-5GI&-5_dvz3EyIW zH4eA0Jq(CGJuo`@pt2J2vPS1z_9IiA?RMwP*`&DDJv#De)b`5$Bn@J1K#>Rg+fgvb z6gNj$(o)MBiobo822-w$+_OxTK+y~uZw$hIm=&D=XPs`qzrV-Mk6Qct`E%O#ox@d7 zje=#VR?y(ko10DToBd`GqlJ)bF8eA8ZuiO_obL&|h)A#UTtWl?n8+WEy*9~-J(+E6_RIL3;Ux{=T=fwBV<*f1+4356+cgRmC4_ZfC!t^wo)p8DpY7&a=s=Rn z$SQQOr+crBIi#22K zlEbbvGg!Eej)U6%#RhF1o%Coue(JkN)cH&D$u%`9eC&0Od|x~Tfkb!?zbBlG%U!;f z4dJ|Wqs1GPxAp=yf~mc=kLy-Mz_5-(WA z8*h4F_UHA-@tmT>Ga{^o4<|ipVLs3Azc62Ec1RQrH?moNb~StJJf{8c=Y+$&Szp}E z3_dTa(@-0^b#vc4WvSbd^Fn6QL)xb0-<+ZLkD_VRkvtzl-9|M=EKU!RSdni|`R z)-f`fEb?oz4chZE#d|vqW!5b1=_ygsAtCC$Pj$J5!))F-^bHM(oPpGeK9#dJ&++l| zo27JB8D+c;U9@dzXoyoy@zcxzWCHYHD`S|L9*w(2P~?v4-$1F5754Y{FP7=Ww1j_o zd{!!?SDTZQ^WHyUKkaxKtm6J9`rb zxLYa&!SPSvbf-8X>0GY)4Kwl?obafh2+=<=M3Sz|kN|WS6BlR0319pc$Sw)}4QgnB z8Y*n@6+ls1rP0+*O`;cC*Vq8J50M?$PR@uhY|D-$KdXlhScBmcVWKl65=l9gU#eX^ z?iy7r=}{bs6bj07S-yL5;6>2yITLOKeSADa`6jVbg)h$(m$8)-RaAY1ECw*iJx;9i z9X_u@K0jK8VS5xa_c>=}mXZxM(LE?x`}55qj0G#JaCLWw*vkuiadEM?zYC!s8J}4r zNwMI-H~F^@w-s!nwOZ$5iT<-)TvCSDuMZn7Yl^}LqN0k-y(V{du%f3|k-m(A(s45?tL#rTZi$Xm#bB&tkCjx@&| z`6aLLBt5^!>mb3>(vk>AzXuu`XvjEb9bl3{ExJ8eV}Ho;2wFVw#t4-4ij7sc`3EQFI}bQ<=6Q zeHK4fBo<| zDw@N+CqiDX-SziBg~QwZv_pz3|7o|ngDjTZP!*N zJ|xnSe9){6&Bc=InsB$7Z0?J@C`loT*BHnP%=&Bm%>Kn&?2iPt}vi>lF zww9f~K?nPe?*nHt36~^2qoXA*wC~8=U-@=qoG6e@sq^Y7c9kNFUAcO-OZzH>6n~2N zKB$lfYp{RiaO$3~Z~e~P+?jmkn_FHXAshMV$_hBTb=0v&@~o*!*6bx4;a1k}k`{JN z8uWaDJsQImb#($TYdPV-%^x;=e0Pr9V;++5u*c@$+RZOO?T7en>t&KmYOa zyjE{!ip|hT?cyuXY+gIov7I_~Dt`AdjbWoCqN=IMiRMo4mihe$B|*8|e2deA54a=G z7BKrwQ`7b)Xjtw|ms;7#6G1;S(^OpDH|q7X`NuUhxAAG{t7&m*$jcgWtb13&VHFFZ zXV0E>8JAkV=o=eLKg=uQI@uZllC!6$2V~JY7A5vG)HxN7?%1A;3dapB%G=vtrp~JY zhet+5g+u#Gm;?H|*J+^>^PV)bo}u8ZoZuW!#l^Z?=TiZ#ZShH90f4WTFrlg-h7P4U zLP{x)N-2gihkCW$>%=4|GZPaN&%(b2QFw8-i@c=9#>UFV#^XRxwR*olpSDsZzlSG$ zU21B7?Jg#QJDXwRWTKz}5SxrX)O_oFVF1#?03~@9oM!|t>pV@V_6A8;I5b{$^5VU} zGysBu-w|7DB!1F6B|C-VN;ewrLV;N9`|VsSy+6fOa`p%gJjD)ke=vO@IFIOmlIYKM zA<2_n;q=EaXTUTSGRSD81qrZ1rmd}wQWp6Wzp9vSdpk2GCw$N+j9h}RzeBqZI@y(M zKCa~Z;C=kZH+?zB64hO44%7e9jIiX6#TJ&KB5cR& zJSa`Wubnoo>@2Gr`cdD}`}%_ZUhmi))DP~ppW60r`|`_lsx_s=h@=7tR#BtyZdB>{ zJMUsy^8pTqL~%99u7w3J!)G?7|3ndIDEh4RYZs@YH%|8FcJ1Z#lw8Do)d%UY{IaIT zbE-XN>4XPFT+VJ+NL$=KbvZ=N=qRX7jgR$CRi7NvB5`%^vWo-?s}e+2Zff1FFW+Cj z+P)gqXwyaX8x79UQ%vftv41tGEX>oh+Ht_L$W+yp5X2nMJafo|`gr1uq6w+nT{W_OHFAZwIMN~)jjlMFotY^|$vTxWd4Jr$V}Jev^yew$ zsN}$%_;SDJ#OpA8;UuWv6zc!|pOjwo`&3njs=Ua0`NaANeDzGpy4B$vV~!RADM;cm zb>1B~a1?9;zLy7d>~AsVqPEP$e*|CBV!+XHAz5J8Rejwh;x_eFZTs%izP>&#?p zh>*&;NH;lO3bN<1d)?i;#j-0CNL4ir|P`j0(RTkhuXw?ivm-b>JUp&HyS;_PJ^p|F%*7<=9+t5iIEeg_xC3diNwxC!jeqxm;a7%A1E*{vG`4q;*Fw8 zj%zjn0jpPeMbC41yzWxTtTva;{TkM$Et#z-BqTJOUNv{foY>Id$;HLhH#o>l-qD!o eihaU7V24#qiE0WTB*%k44=@uWOG5(MHQ|4)PGigf diff --git a/data/interfaces/default/index.html b/data/interfaces/default/index.html index 16a97a30..68fb3492 100644 --- a/data/interfaces/default/index.html +++ b/data/interfaces/default/index.html @@ -53,7 +53,7 @@ %>

      - + diff --git a/data/interfaces/default/js/script.js b/data/interfaces/default/js/script.js index a89bb618..85ad59d2 100644 --- a/data/interfaces/default/js/script.js +++ b/data/interfaces/default/js/script.js @@ -2,8 +2,10 @@ function getThumb(imgElem,id,type) { if ( type == 'artist' ) { var thumbURL = "getThumb?ArtistID=" + id; + // var imgURL = "getArtwork?ArtistID=" + id; } else { var thumbURL = "getThumb?AlbumID=" + id; + // var imgURL = "getArtwork?AlbumID=" + id; } // Get Data from the cache by Artist ID $.ajax({ @@ -15,9 +17,9 @@ function getThumb(imgElem,id,type) { } else { var imageUrl = data; - } + } $(imgElem).attr("src",imageUrl).hide().fadeIn(); - // $(imgElem).wrap(''); + // $(imgElem).wrap(''); } }); } @@ -34,12 +36,12 @@ function getArtwork(imgElem,id,name,type) { url: artworkURL, cache: true, success: function(data){ - if ( data == "" ) { + if ( data == "" || data == undefined ) { var imageUrl = "interfaces/default/images/no-cover-artist.png"; } else { var imageUrl = data; - } + } $(imgElem).attr("src",imageUrl).hide().fadeIn(); $(imgElem).wrap(''); } @@ -78,20 +80,23 @@ function getImageLinks(elem,id,type) { cache: true, dataType: "json", success: function(data){ - var thumbnail = data.thumbnail; - var artwork = data.artwork; - + if ( data.thumbnail == "" || data.thumbnail == undefined ) { + var thumbnail = "interfaces/default/images/no-cover-artist.png"; + } + else { + var thumbnail = data.thumbnail; + } + if ( data.artwork == "" || data.artwork == undefined ) { + var artwork = "interfaces/default/images/no-cover-artist.png"; + } + else { + var artwork = data.artwork; + } $(elem).attr("src", thumbnail); } }); } -function getOriginalWidthOfImg(img_element) { - var t = new Image(); - t.src = (img_element.getAttribute ? img_element.getAttribute("src") : false) || img_element.src; - return t.width; -} - function initHeader() { //settings var header = $("#container header"); @@ -339,7 +344,7 @@ function initFancybox() { if ( $("a[rel=dialog]").length > 0 ) { $.getScript('interfaces/default/js/fancybox/jquery.fancybox-1.3.4.js', function() { $("head").append(""); - $("a[rel=dialog]").fancybox(); + $("a[rel=dialog]").fancybox({}); }); } } diff --git a/data/interfaces/default/upcoming.html b/data/interfaces/default/upcoming.html index bbe3e312..69f75c4c 100644 --- a/data/interfaces/default/upcoming.html +++ b/data/interfaces/default/upcoming.html @@ -40,7 +40,7 @@ %for album in wanted: + @@ -70,7 +70,7 @@ %for album in upcoming: - + From ee441f334e0c80be305c0e6cb6dccdcd71a725b0 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 26 Jun 2012 19:11:13 +0530 Subject: [PATCH 48/52] Updated README with new screenshots, link to new forum --- README.md | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 56e453be..69d2b9a6 100644 --- a/README.md +++ b/README.md @@ -2,33 +2,44 @@ ###Installation and Notes -This is a pretty early release of a third-party add-on for SABnzbd. +This is a relatively early release of a third-party add-on for SABnzbd. It's been around for about a year, and while +quite functional, there are still a lot of kinks to work out! To run it, just double-click the Headphones.py file (in Windows - you may need to right click and click 'Open With' -> Python) or launch a terminal, cd into the Headphones directory and run 'python headphones.py'. For additional startup options, type 'python Headphones.py -h' or 'python Headphones.py --help' ###Screenshots -(note: These screenshots are a little out of date and the interface has gone through a little bit of an overhaul. Updated shots coming soon!) -First Run +Homepage (Artist Overview) -![preview thumb](http://img806.imageshack.us/img806/4202/headphones2.png) +![preview thumb](http://i.imgur.com/7VHuO.png) -Artist Search Results +One of the many settings pages.... -![preview thumb](http://img12.imageshack.us/img12/7838/headphones4.png) +![preview thumb](http://i.imgur.com/l0AYz.png) -Album Selection +It might even know you better than you know yourself: -![preview thumb](http://img836.imageshack.us/img836/2880/headphones3.png) +![preview thumb](http://i.imgur.com/LALaa.png) -iTunes/Import +Import Your Artists: -![preview thumb](http://img62.imageshack.us/img62/1218/headphones1.png) +![preview thumb](http://i.imgur.com/rvkD4.png) -If you run into any issues, visit http://github.com/rembo10/headphones and report an issue. +Artist Search Results (also search by album!): -This is free software so feel free to use it/modify it as you wish. +![preview thumb](http://i.imgur.com/1mTzO.png) -If you have any ideas for the next release, also make sure to post that here! \ No newline at end of file +Artist Page with Bio & Album Overview: + +![preview thumb](http://i.imgur.com/5j7Jh.png) +![preview thumb](http://i.imgur.com/mSKEJ.png) + +Album Page with track overview: + +![preview thumb](http://i.imgur.com/CUy4e.png) + +If you run into any issues, visit http://headphones.codeshy.com/forum and report an issue. + +This is free software under the GPL v3 open source license - so feel free to do with it what you wish. From ac85236f3673a8a2b55156a82f07a5505a1eb029 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 26 Jun 2012 19:17:41 +0530 Subject: [PATCH 49/52] fancybox fix --- data/interfaces/default/js/script.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data/interfaces/default/js/script.js b/data/interfaces/default/js/script.js index 85ad59d2..b1ac046d 100644 --- a/data/interfaces/default/js/script.js +++ b/data/interfaces/default/js/script.js @@ -344,7 +344,7 @@ function initFancybox() { if ( $("a[rel=dialog]").length > 0 ) { $.getScript('interfaces/default/js/fancybox/jquery.fancybox-1.3.4.js', function() { $("head").append(""); - $("a[rel=dialog]").fancybox({}); + $("a[rel=dialog]").fancybox(); }); } } From 408cb7d1fc9f3758eca1ba6781db722ca3ce8498 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 26 Jun 2012 19:30:49 +0530 Subject: [PATCH 50/52] Updated README with new screenshots :-) --- README.md | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 69d2b9a6..60116063 100644 --- a/README.md +++ b/README.md @@ -13,32 +13,31 @@ For additional startup options, type 'python Headphones.py -h' or 'python Headph Homepage (Artist Overview) -![preview thumb](http://i.imgur.com/7VHuO.png) +![preview thumb](http://i.imgur.com/LZO9a.png) One of the many settings pages.... -![preview thumb](http://i.imgur.com/l0AYz.png) +![preview thumb](http://i.imgur.com/xcWNy.png) It might even know you better than you know yourself: -![preview thumb](http://i.imgur.com/LALaa.png) +![preview thumb](http://i.imgur.com/R7J0f.png) -Import Your Artists: +Import Your Favorite Artists: -![preview thumb](http://i.imgur.com/rvkD4.png) +![preview thumb](http://i.imgur.com/6tZoC.png) Artist Search Results (also search by album!): -![preview thumb](http://i.imgur.com/1mTzO.png) +![preview thumb](http://i.imgur.com/rIV0P.png) Artist Page with Bio & Album Overview: -![preview thumb](http://i.imgur.com/5j7Jh.png) -![preview thumb](http://i.imgur.com/mSKEJ.png) +![preview thumb](http://i.imgur.com/SSil1.png) Album Page with track overview: -![preview thumb](http://i.imgur.com/CUy4e.png) +![preview thumb](http://i.imgur.com/kcjES.png) If you run into any issues, visit http://headphones.codeshy.com/forum and report an issue. From 2aefb55a1a9ec54cbd3eebfbbfa9f0219728e0df Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 26 Jun 2012 19:46:21 +0530 Subject: [PATCH 51/52] Changed log level for cache updates to debug --- headphones/importer.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/headphones/importer.py b/headphones/importer.py index fa541970..73ececfd 100644 --- a/headphones/importer.py +++ b/headphones/importer.py @@ -218,7 +218,7 @@ def addArtisttoDB(artistid, extrasonly=False): myDB.upsert("tracks", newValueDict, controlValueDict) - logger.info(u"Updating album cache for " + rg['title']) + logger.debug(u"Updating album cache for " + rg['title']) cache.getThumb(AlbumID=rg['id']) latestalbum = myDB.action('SELECT AlbumTitle, ReleaseDate, AlbumID from albums WHERE ArtistID=? order by ReleaseDate DESC', [artistid]).fetchone() @@ -243,7 +243,7 @@ def addArtisttoDB(artistid, extrasonly=False): myDB.upsert("artists", newValueDict, controlValueDict) - logger.info(u"Updating cache for: " + artist['artist_name']) + logger.debug(u"Updating cache for: " + artist['artist_name']) cache.getThumb(ArtistID=artistid) logger.info(u"Updating complete for: " + artist['artist_name']) From 9cc5dbb4a2c4ca904d77de2753d86f74cd135450 Mon Sep 17 00:00:00 2001 From: rembo10 Date: Tue, 26 Jun 2012 20:29:02 +0530 Subject: [PATCH 52/52] Fixed some of the log levels in the music_encoder --- headphones/music_encoder.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/headphones/music_encoder.py b/headphones/music_encoder.py index 93b56e23..20e995e1 100644 --- a/headphones/music_encoder.py +++ b/headphones/music_encoder.py @@ -52,7 +52,7 @@ def encode(albumPath): musicTemp = os.path.normpath(os.path.splitext(music)[0]+'.'+headphones.ENCODEROUTPUTFORMAT).encode(headphones.SYS_ENCODING) musicTempFiles.append(os.path.join(tempDirEncode, musicTemp)) else: - logger.warn('Music "%s" is already encoded' % (music)) + logger.debug('Music "%s" is already encoded' % (music)) else: musicFiles.append(os.path.join(r, music)) musicTemp = os.path.normpath(os.path.splitext(music)[0]+'.'+headphones.ENCODEROUTPUTFORMAT).encode(headphones.SYS_ENCODING) @@ -70,7 +70,7 @@ def encode(albumPath): logger.warn('Lame cant encode "%s" format for "%s", use ffmpeg' % (os.path.splitext(music)[1],music)) else: if (music.lower().endswith('.mp3') and (infoMusic.bitrate/1000<=headphones.BITRATE)): - logger.warn('Music "%s" has bitrate<="%skbit" will not be reencoded' % (music,headphones.BITRATE)) + logger.info('Music "%s" has bitrate<="%skbit" will not be reencoded' % (music,headphones.BITRATE)) else: command(encoder,music,musicTempFiles[i],albumPath) ifencoded=1 @@ -83,7 +83,7 @@ def encode(albumPath): ifencoded=1 elif (headphones.ENCODEROUTPUTFORMAT=='mp3' or headphones.ENCODEROUTPUTFORMAT=='m4a'): if (music.lower().endswith('.'+headphones.ENCODEROUTPUTFORMAT) and (infoMusic.bitrate/1000<=headphones.BITRATE)): - logger.warn('Music "%s" has bitrate<="%skbit" will not be reencoded' % (music,headphones.BITRATE)) + logger.info('Music "%s" has bitrate<="%skbit" will not be reencoded' % (music,headphones.BITRATE)) else: command(encoder,music,musicTempFiles[i],albumPath) ifencoded=1
      ${artist['ArtistName']} ${artist['Status']} ${albumdisplay}
      - ${album['ArtistName']} ${album['AlbumTitle']} ${album['ReleaseDate']}
      ${album['ArtistName']} ${album['AlbumTitle']} ${album['ReleaseDate']}