From 7726044c6169897074d3d82863b8d249bcd55506 Mon Sep 17 00:00:00 2001 From: Jesse Mullan Date: Sat, 1 Nov 2014 16:28:44 -0700 Subject: [PATCH] Fix whitespace around arithmetic operator --- headphones/cache.py | 2 +- headphones/classes.py | 2 +- headphones/common.py | 10 ++++----- headphones/cuesplit.py | 16 +++++++------- headphones/db.py | 6 +++--- headphones/helpers.py | 12 +++++------ headphones/importer.py | 8 +++---- headphones/librarysync.py | 12 +++++------ headphones/mb.py | 20 +++++++++--------- headphones/music_encoder.py | 10 ++++----- headphones/notifiers.py | 42 ++++++++++++++++++------------------- headphones/postprocessor.py | 2 +- headphones/sab.py | 8 +++---- headphones/searcher.py | 14 ++++++------- headphones/transmission.py | 2 +- headphones/versioncheck.py | 10 ++++----- headphones/webserve.py | 20 +++++++++--------- 17 files changed, 98 insertions(+), 98 deletions(-) diff --git a/headphones/cache.py b/headphones/cache.py index 13bdf775..73c7fc40 100644 --- a/headphones/cache.py +++ b/headphones/cache.py @@ -89,7 +89,7 @@ class Cache(object): 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]) + days_old = int(split_date[0]) * 365 + int(split_date[1]) * 30 + int(split_date[2]) return days_old diff --git a/headphones/classes.py b/headphones/classes.py index 7d269741..d9665090 100644 --- a/headphones/classes.py +++ b/headphones/classes.py @@ -135,4 +135,4 @@ class Proper: self.episode = -1 def __str__(self): - return str(self.date)+" "+self.name+" "+str(self.season)+"x"+str(self.episode)+" of "+str(self.tvdbid) + return str(self.date) + " " + self.name + " " + str(self.season) + "x" + str(self.episode) + " of " + str(self.tvdbid) diff --git a/headphones/common.py b/headphones/common.py index 28f1a7ff..bc6c9554 100644 --- a/headphones/common.py +++ b/headphones/common.py @@ -23,7 +23,7 @@ import platform, operator, os, re from headphones import version #Identify Our Application -USER_AGENT = 'Headphones/-'+version.HEADPHONES_VERSION+' ('+platform.system()+' '+platform.release()+')' +USER_AGENT = 'Headphones/-' + version.HEADPHONES_VERSION + ' (' + platform.system() + ' ' + platform.release() + ')' ### Notification Types NOTIFY_SNATCH = 1 @@ -72,7 +72,7 @@ class Quality: def _getStatusStrings(status): toReturn = {} for x in Quality.qualityStrings.keys(): - toReturn[Quality.compositeStatus(status, x)] = Quality.statusPrefixes[status]+" ("+Quality.qualityStrings[x]+")" + toReturn[Quality.compositeStatus(status, x)] = Quality.statusPrefixes[status] + " (" + Quality.qualityStrings[x] + ")" return toReturn @staticmethod @@ -107,7 +107,7 @@ class Quality: if x == Quality.UNKNOWN: continue - regex = '\W'+Quality.qualityStrings[x].replace(' ', '\W')+'\W' + regex = '\W' + Quality.qualityStrings[x].replace(' ', '\W') + '\W' regex_match = re.search(regex, name, re.I) if regex_match: return x @@ -148,8 +148,8 @@ class Quality: def splitCompositeStatus(status): """Returns a tuple containing (status, quality)""" for x in sorted(Quality.qualityStrings.keys(), reverse=True): - if status > x*100: - return (status-x*100, x) + if status > x * 100: + return (status - x * 100, x) return (Quality.NONE, status) diff --git a/headphones/cuesplit.py b/headphones/cuesplit.py index 0833a138..33da38e8 100755 --- a/headphones/cuesplit.py +++ b/headphones/cuesplit.py @@ -147,7 +147,7 @@ def check_list(list, ignore=0): except: break - return tuple(list1+list2) + return tuple(list1 + list2) def trim_cue_entry(string): @@ -179,7 +179,7 @@ def split_file_list(ext=None): if (ext and ext == os.path.splitext(f)[-1]) or not ext: filename_parser = re.search('split-track(\d\d)', f) track_nr = int(filename_parser.group(1)) - if cue.htoa() and not os.path.exists('split-track00'+ext): + if cue.htoa() and not os.path.exists('split-track00' + ext): track_nr -= 1 file_list[track_nr] = WaveFile(f, track_nr=track_nr) return check_list(file_list, ignore=1) @@ -326,7 +326,7 @@ class CueFile(File): line_content = c[line_index] search_result = re.search(CUE_TRACK, line_content, re.I) if not search_result: - raise ValueError('inconsistent CUE sheet, TRACK expected at line {0}'.format(line_index+1)) + raise ValueError('inconsistent CUE sheet, TRACK expected at line {0}'.format(line_index + 1)) track_nr = int(search_result.group(1)) line_index += 1 next_track = False @@ -358,14 +358,14 @@ class CueFile(File): line_index += 1 elif re.search(CUE_TRACK, line_content, re.I): next_track = True - elif line_index == len(c)-1 and not line_content: + elif line_index == len(c) - 1 and not line_content: # last line is empty line_index += 1 elif re.search('FLAGS DCP$', line_content, re.I): track_meta['dcpflag'] = True line_index += 1 else: - raise ValueError('unknown entry in track error, line {0}'.format(line_index+1)) + raise ValueError('unknown entry in track error, line {0}'.format(line_index + 1)) else: next_track = True @@ -418,9 +418,9 @@ class CueFile(File): for i in range(len(self.tracks)): if self.tracks[i]: if self.tracks[i].get('artist'): - content += 'track'+int_to_str(i) + 'artist' + '\t' + self.tracks[i].get('artist') + '\n' + content += 'track' + int_to_str(i) + 'artist' + '\t' + self.tracks[i].get('artist') + '\n' if self.tracks[i].get('title'): - content += 'track'+int_to_str(i) + 'title' + '\t' + self.tracks[i].get('title') + '\n' + content += 'track' + int_to_str(i) + 'title' + '\t' + self.tracks[i].get('title') + '\n' return content def htoa(self): @@ -478,7 +478,7 @@ class MetaFile(File): common_tags['album'] = self.content['title'] common_tags['title'] = self.content['tracks'][track_nr]['title'] common_tags['tracknumber'] = str(track_nr) - common_tags['tracktotal'] = str(len(self.content['tracks'])-1) + common_tags['tracktotal'] = str(len(self.content['tracks']) - 1) if 'date' in self.content: common_tags['date'] = self.content['date'] if 'genre' in meta.content: diff --git a/headphones/db.py b/headphones/db.py index 2d113088..b1eac471 100644 --- a/headphones/db.py +++ b/headphones/db.py @@ -53,7 +53,7 @@ class DBConnection: #journal disabled since we never do rollbacks self.connection.execute("PRAGMA journal_mode = %s" % headphones.CONFIG.JOURNAL_MODE) #64mb of cache memory,probably need to make it user configurable - self.connection.execute("PRAGMA cache_size=-%s" % (getCacheSize()*1024)) + self.connection.execute("PRAGMA cache_size=-%s" % (getCacheSize() * 1024)) self.connection.row_factory = sqlite3.Row def action(self, query, args=None): @@ -98,11 +98,11 @@ class DBConnection: genParams = lambda myDict: [x + " = ?" for x in myDict.keys()] - query = "UPDATE "+tableName+" SET " + ", ".join(genParams(valueDict)) + " WHERE " + " AND ".join(genParams(keyDict)) + 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()) + ")" + \ + 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 4fa66a92..87026ddd 100644 --- a/headphones/helpers.py +++ b/headphones/helpers.py @@ -105,7 +105,7 @@ def latinToAscii(unicrap): def convert_milliseconds(ms): - seconds = ms/1000 + seconds = ms / 1000 gmtime = time.gmtime(seconds) if seconds > 3600: minutes = time.strftime("%H:%M:%S", gmtime) @@ -145,7 +145,7 @@ def get_age(date): return False try: - days_old = int(split_date[0])*365 + int(split_date[1])*30 + int(split_date[2]) + days_old = int(split_date[0]) * 365 + int(split_date[1]) * 30 + int(split_date[2]) except IndexError: days_old = False @@ -154,7 +154,7 @@ def get_age(date): def bytes_to_mb(bytes): - mb = int(bytes)/1048576 + mb = int(bytes) / 1048576 size = '%.1f MB' % mb return size @@ -162,7 +162,7 @@ def bytes_to_mb(bytes): def mb_to_bytes(mb_str): result = re.search('^(\d+(?:\.\d+)?)\s?(?:mb)?', mb_str, flags=re.I) if result: - return int(float(result.group(1))*1048576) + return int(float(result.group(1)) * 1048576) def piratesize(size): @@ -689,12 +689,12 @@ def create_https_certificates(ssl_cert, ssl_key): # Create the CA Certificate cakey = createKeyPair(TYPE_RSA, 1024) careq = createCertRequest(cakey, CN='Certificate Authority') - cacert = createCertificate(careq, (careq, cakey), serial, (0, 60*60*24*365*10)) # ten years + cacert = createCertificate(careq, (careq, cakey), serial, (0, 60 * 60 * 24 * 365 * 10)) # ten years cname = 'Headphones' pkey = createKeyPair(TYPE_RSA, 1024) req = createCertRequest(pkey, CN=cname) - cert = createCertificate(req, (cacert, cakey), serial, (0, 60*60*24*365*10)) # ten years + cert = createCertificate(req, (cacert, cakey), serial, (0, 60 * 60 * 24 * 365 * 10)) # ten years # Save the key and certificate to disk try: diff --git a/headphones/importer.py b/headphones/importer.py index 495b610c..c5fdda0b 100644 --- a/headphones/importer.py +++ b/headphones/importer.py @@ -253,9 +253,9 @@ def addArtisttoDB(artistid, extrasonly=False, forcefull=False): if len(check_release_date) == 10: release_date = check_release_date elif len(check_release_date) == 7: - release_date = check_release_date+"-31" + release_date = check_release_date + "-31" elif len(check_release_date) == 4: - release_date = check_release_date+"-12-31" + release_date = check_release_date + "-12-31" else: release_date = today if helpers.get_age(today) - helpers.get_age(release_date) < pause_delta: @@ -464,11 +464,11 @@ def addArtisttoDB(artistid, extrasonly=False, forcefull=False): marked_as_downloaded = False if rg_exists: - if rg_exists['Status'] == 'Skipped' and ((have_track_count/float(total_track_count)) >= (headphones.CONFIG.ALBUM_COMPLETION_PCT/100.0)): + if rg_exists['Status'] == 'Skipped' and ((have_track_count / float(total_track_count)) >= (headphones.CONFIG.ALBUM_COMPLETION_PCT / 100.0)): myDB.action('UPDATE albums SET Status=? WHERE AlbumID=?', ['Downloaded', rg['id']]) marked_as_downloaded = True else: - if ((have_track_count/float(total_track_count)) >= (headphones.CONFIG.ALBUM_COMPLETION_PCT/100.0)): + if ((have_track_count / float(total_track_count)) >= (headphones.CONFIG.ALBUM_COMPLETION_PCT / 100.0)): myDB.action('UPDATE albums SET Status=? WHERE AlbumID=?', ['Downloaded', rg['id']]) marked_as_downloaded = True diff --git a/headphones/librarysync.py b/headphones/librarysync.py index a0f97431..c13fef17 100644 --- a/headphones/librarysync.py +++ b/headphones/librarysync.py @@ -96,7 +96,7 @@ def libraryScan(dir=None, append=False, ArtistID=None, ArtistName=None, cron=Fal latest_subdirectory.append(subdirectory) if file_count == 0 and r.replace(dir, '') != '': logger.info("[%s] Now scanning subdirectory %s" % (dir.decode(headphones.SYS_ENCODING, 'replace'), subdirectory.decode(headphones.SYS_ENCODING, 'replace'))) - elif latest_subdirectory[file_count] != latest_subdirectory[file_count-1] and file_count != 0: + elif latest_subdirectory[file_count] != latest_subdirectory[file_count - 1] and file_count != 0: logger.info("[%s] Now scanning subdirectory %s" % (dir.decode(headphones.SYS_ENCODING, 'replace'), subdirectory.decode(headphones.SYS_ENCODING, 'replace'))) song = os.path.join(r, files) @@ -183,8 +183,8 @@ def libraryScan(dir=None, append=False, ArtistID=None, ArtistName=None, cron=Fal # Now we start track matching logger.info("%s new/modified songs found and added to the database" % new_song_count) - song_list = myDB.action("SELECT * FROM have WHERE Matched IS NULL AND LOCATION LIKE ?", [dir.decode(headphones.SYS_ENCODING, 'replace')+"%"]) - total_number_of_songs = myDB.action("SELECT COUNT(*) FROM have WHERE Matched IS NULL AND LOCATION LIKE ?", [dir.decode(headphones.SYS_ENCODING, 'replace')+"%"]).fetchone()[0] + song_list = myDB.action("SELECT * FROM have WHERE Matched IS NULL AND LOCATION LIKE ?", [dir.decode(headphones.SYS_ENCODING, 'replace') + "%"]) + total_number_of_songs = myDB.action("SELECT COUNT(*) FROM have WHERE Matched IS NULL AND LOCATION LIKE ?", [dir.decode(headphones.SYS_ENCODING, 'replace') + "%"]).fetchone()[0] logger.info("Found " + str(total_number_of_songs) + " new/modified tracks in: '" + dir.decode(headphones.SYS_ENCODING, 'replace') + "'. Matching tracks to the appropriate releases....") # Sort the song_list by most vague (e.g. no trackid or releaseid) to most specific (both trackid & releaseid) @@ -202,11 +202,11 @@ def libraryScan(dir=None, append=False, ArtistID=None, ArtistName=None, cron=Fal latest_artist.append(song['ArtistName']) if song_count == 0: logger.info("Now matching songs by %s" % song['ArtistName']) - elif latest_artist[song_count] != latest_artist[song_count-1] and song_count != 0: + elif latest_artist[song_count] != latest_artist[song_count - 1] and song_count != 0: logger.info("Now matching songs by %s" % song['ArtistName']) song_count += 1 - completion_percentage = float(song_count)/total_number_of_songs * 100 + completion_percentage = float(song_count) / total_number_of_songs * 100 if completion_percentage % 10 == 0: logger.info("Track matching is " + str(completion_percentage) + "% complete") @@ -327,7 +327,7 @@ def libraryScan(dir=None, append=False, ArtistID=None, ArtistName=None, cron=Fal myDB.action('INSERT OR IGNORE INTO newartists VALUES (?)', [artist]) if headphones.CONFIG.DETECT_BITRATE: - headphones.CONFIG.PREFERRED_BITRATE = sum(bitrates)/len(bitrates)/1000 + headphones.CONFIG.PREFERRED_BITRATE = sum(bitrates) / len(bitrates) / 1000 else: # If we're appending a new album to the database, update the artists total track counts diff --git a/headphones/mb.py b/headphones/mb.py index cca475bb..19d9766c 100644 --- a/headphones/mb.py +++ b/headphones/mb.py @@ -84,7 +84,7 @@ def findArtist(name, limit=1): chars = set('!?*-') if any((c in chars) for c in name): - name = '"'+name+'"' + name = '"' + name + '"' criteria = {'artist': name.lower()} @@ -139,9 +139,9 @@ def findRelease(name, limit=1, artist=None): chars = set('!?*-') if any((c in chars) for c in name): - name = '"'+name+'"' + name = '"' + name + '"' if artist and any((c in chars) for c in artist): - artist = '"'+artist+'"' + artist = '"' + artist + '"' try: releaseResults = musicbrainzngs.search_releases(query=name, limit=limit, artist=artist)['release-list'] @@ -500,12 +500,12 @@ def get_new_releases(rgid, includeExtras=False, forcefull=False): if position['format'] == releasedata['medium-list'][0]['format']: medium_count = int(position['position']) else: - additional_medium = additional_medium+' + '+position['format'] + additional_medium = additional_medium + ' + ' + position['format'] if medium_count == 1: disc_number = '' else: - disc_number = str(medium_count)+'x' - packaged_medium = disc_number+releasedata['medium-list'][0]['format']+additional_medium + disc_number = str(medium_count) + 'x' + packaged_medium = disc_number + releasedata['medium-list'][0]['format'] + additional_medium release['ReleaseFormat'] = unicode(packaged_medium) except: release['ReleaseFormat'] = u'Unknown' @@ -611,7 +611,7 @@ def findArtistbyAlbum(name): if not artist['AlbumTitle']: return False - term = '"'+artist['AlbumTitle']+'" AND artist:"'+name+'"' + term = '"' + artist['AlbumTitle'] + '" AND artist:"' + name + '"' results = None @@ -649,14 +649,14 @@ def findAlbumID(artist=None, album=None): try: if album and artist: if any((c in chars) for c in album): - album = '"'+album+'"' + album = '"' + album + '"' if any((c in chars) for c in artist): - artist = '"'+artist+'"' + artist = '"' + artist + '"' criteria = {'release': album.lower()} criteria['artist'] = artist.lower() else: if any((c in chars) for c in album): - album = '"'+album+'"' + album = '"' + album + '"' criteria = {'release': album.lower()} results = musicbrainzngs.search_release_groups(limit=1, **criteria).get('release-group-list') diff --git a/headphones/music_encoder.py b/headphones/music_encoder.py index ee5dcb71..b5f606cb 100644 --- a/headphones/music_encoder.py +++ b/headphones/music_encoder.py @@ -131,7 +131,7 @@ def encode(albumPath): else: encode = True elif (headphones.CONFIG.ENCODEROUTPUTFORMAT == 'mp3' or headphones.CONFIG.ENCODEROUTPUTFORMAT == 'm4a'): - if (music.decode(headphones.SYS_ENCODING, 'replace').lower().endswith('.'+headphones.CONFIG.ENCODEROUTPUTFORMAT) and (int(infoMusic.bitrate / 1000) <= headphones.CONFIG.BITRATE)): + if (music.decode(headphones.SYS_ENCODING, 'replace').lower().endswith('.' + headphones.CONFIG.ENCODEROUTPUTFORMAT) and (int(infoMusic.bitrate / 1000) <= headphones.CONFIG.BITRATE)): logger.info('%s has bitrate <= %skb, will not be re-encoded', music, headphones.CONFIG.BITRATE) else: encode = True @@ -143,7 +143,7 @@ def encode(albumPath): musicFiles[i] = None musicTempFiles[i] = None - i = i+1 + i = i + 1 # Encode music files if len(jobs) > 0: @@ -362,9 +362,9 @@ def command(encoder, musicSource, musicDest, albumPath): def getTimeEncode(start): - seconds = int(time.time()-start) + seconds = int(time.time() - start) hours = seconds / 3600 - seconds -= 3600*hours + seconds -= 3600 * hours minutes = seconds / 60 - seconds -= 60*minutes + seconds -= 60 * minutes return "%02d:%02d:%02d" % (hours, minutes, seconds) diff --git a/headphones/notifiers.py b/headphones/notifiers.py index e92177e7..f744e252 100644 --- a/headphones/notifiers.py +++ b/headphones/notifiers.py @@ -233,7 +233,7 @@ class XBMC(object): hosts = [x.strip() for x in self.hosts.split(',')] for host in hosts: - logger.info('Sending library update command to XBMC @ '+host) + logger.info('Sending library update command to XBMC @ ' + host) request = self._sendjson(host, 'AudioLibrary.Scan') if not request: @@ -248,13 +248,13 @@ class XBMC(object): time = "3000" # in ms for host in hosts: - logger.info('Sending notification command to XMBC @ '+host) + logger.info('Sending notification command to XMBC @ ' + host) try: version = self._sendjson(host, 'Application.GetProperties', {'properties': ['version']})['version']['major'] if version < 12: #Eden notification = header + "," + message + "," + time + "," + albumartpath - notifycommand = {'command': 'ExecBuiltIn', 'parameter': 'Notification('+notification+')'} + notifycommand = {'command': 'ExecBuiltIn', 'parameter': 'Notification(' + notification + ')'} request = self._sendhttp(host, notifycommand) else: #Frodo @@ -282,7 +282,7 @@ class LMS(object): content = {'Content-Type': 'application/json'} - req = urllib2.Request(host+'/jsonrpc.js', data, content) + req = urllib2.Request(host + '/jsonrpc.js', data, content) try: handle = urllib2.urlopen(req) @@ -303,7 +303,7 @@ class LMS(object): hosts = [x.strip() for x in self.hosts.split(',')] for host in hosts: - logger.info('Sending library rescan command to LMS @ '+host) + logger.info('Sending library rescan command to LMS @ ' + host) request = self._sendjson(host) if not request: @@ -353,7 +353,7 @@ class Plex(object): hosts = [x.strip() for x in self.server_hosts.split(',')] for host in hosts: - logger.info('Sending library update command to Plex Media Server@ '+host) + logger.info('Sending library update command to Plex Media Server@ ' + host) url = "%s/library/sections" % host try: xml_sections = minidom.parse(urllib.urlopen(url)) @@ -384,10 +384,10 @@ class Plex(object): time = "3000" # in ms for host in hosts: - logger.info('Sending notification command to Plex Media Server @ '+host) + logger.info('Sending notification command to Plex Media Server @ ' + host) try: notification = header + "," + message + "," + time + "," + albumartpath - notifycommand = {'command': 'ExecBuiltIn', 'parameter': 'Notification('+notification+')'} + notifycommand = {'command': 'ExecBuiltIn', 'parameter': 'Notification(' + notification + ')'} request = self._sendhttp(host, notifycommand) if not request: @@ -638,14 +638,14 @@ class TwitterNotifier(object): def notify_snatch(self, title): if headphones.CONFIG.TWITTER_ONSNATCH: - self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title+' at '+helpers.now()) + self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH] + ': ' + title + ' at ' + helpers.now()) def notify_download(self, title): if headphones.CONFIG.TWITTER_ENABLED: - self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title+' at '+helpers.now()) + self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD] + ': ' + title + ' at ' + helpers.now()) def test_notify(self): - return self._notifyTwitter("This is a test notification from Headphones at "+helpers.now(), force=True) + return self._notifyTwitter("This is a test notification from Headphones at " + helpers.now(), force=True) def _get_authorization(self): @@ -665,7 +665,7 @@ class TwitterNotifier(object): headphones.CONFIG.TWITTER_USERNAME = request_token['oauth_token'] headphones.CONFIG.TWITTER_PASSWORD = request_token['oauth_token_secret'] - return self.AUTHORIZATION_URL+"?oauth_token=" + request_token['oauth_token'] + return self.AUTHORIZATION_URL + "?oauth_token=" + request_token['oauth_token'] def _get_credentials(self, key): request_token = {} @@ -677,22 +677,22 @@ class TwitterNotifier(object): token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) - logger.info('Generating and signing request for an access token using key '+key) + logger.info('Generating and signing request for an access token using key ' + key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) - logger.info('oauth_consumer: '+str(oauth_consumer)) + logger.info('oauth_consumer: ' + str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) - logger.info('oauth_client: '+str(oauth_client)) + logger.info('oauth_client: ' + str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) - logger.info('resp, content: '+str(resp)+','+str(content)) + logger.info('resp, content: ' + str(resp) + ',' + str(content)) access_token = dict(parse_qsl(content)) - logger.info('access_token: '+str(access_token)) + logger.info('access_token: ' + str(access_token)) - logger.info('resp[status] = '+str(resp['status'])) + logger.info('resp[status] = ' + str(resp['status'])) if resp['status'] != '200': - logger.info('The request for a token with did not succeed: '+str(resp['status']), logger.ERROR) + logger.info('The request for a token with did not succeed: ' + str(resp['status']), logger.ERROR) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) @@ -708,7 +708,7 @@ class TwitterNotifier(object): access_token_key = headphones.CONFIG.TWITTER_USERNAME access_token_secret = headphones.CONFIG.TWITTER_PASSWORD - logger.info(u"Sending tweet: "+message) + logger.info(u"Sending tweet: " + message) api = twitter.Api(username, password, access_token_key, access_token_secret) @@ -726,7 +726,7 @@ class TwitterNotifier(object): if not headphones.CONFIG.TWITTER_ENABLED and not force: return False - return self._send_tweet(prefix+": "+message) + return self._send_tweet(prefix + ": " + message) class OSX_NOTIFY(object): diff --git a/headphones/postprocessor.py b/headphones/postprocessor.py index f699b607..88f79d33 100755 --- a/headphones/postprocessor.py +++ b/headphones/postprocessor.py @@ -249,7 +249,7 @@ def verify(albumid, albumpath, Kind=None, forced=False): for track in tracks: try: - db_track_duration += track['TrackDuration']/1000 + db_track_duration += track['TrackDuration'] / 1000 except: downloaded_track_duration = False break diff --git a/headphones/sab.py b/headphones/sab.py index 632ea320..7f64041f 100644 --- a/headphones/sab.py +++ b/headphones/sab.py @@ -50,7 +50,7 @@ def sendNZB(nzb): if nzb.provider.getID() == 'newzbin': id = nzb.provider.getIDFromURL(nzb.url) if not id: - logger.info("Unable to send NZB to sab, can't find ID in URL "+str(nzb.url)) + logger.info("Unable to send NZB to sab, can't find ID in URL " + str(nzb.url)) return False params['mode'] = 'addid' params['name'] = id @@ -63,13 +63,13 @@ def sendNZB(nzb): # Sanitize the file a bit, since we can only use ascii chars with MultiPartPostHandler nzbdata = helpers.latinToAscii(nzb.extraInfo[0]) params['mode'] = 'addfile' - multiPartParams = {"nzbfile": (helpers.latinToAscii(nzb.name)+".nzb", nzbdata)} + multiPartParams = {"nzbfile": (helpers.latinToAscii(nzb.name) + ".nzb", nzbdata)} if not headphones.CONFIG.SAB_HOST.startswith('http'): headphones.CONFIG.SAB_HOST = 'http://' + headphones.CONFIG.SAB_HOST if headphones.CONFIG.SAB_HOST.endswith('/'): - headphones.CONFIG.SAB_HOST = headphones.CONFIG.SAB_HOST[0:len(headphones.CONFIG.SAB_HOST)-1] + headphones.CONFIG.SAB_HOST = headphones.CONFIG.SAB_HOST[0:len(headphones.CONFIG.SAB_HOST) - 1] url = headphones.CONFIG.SAB_HOST + "/" + "api?" + urllib.urlencode(params) @@ -146,7 +146,7 @@ def checkConfig(): headphones.CONFIG.SAB_HOST = 'http://' + headphones.CONFIG.SAB_HOST if headphones.CONFIG.SAB_HOST.endswith('/'): - headphones.CONFIG.SAB_HOST = headphones.CONFIG.SAB_HOST[0:len(headphones.CONFIG.SAB_HOST)-1] + headphones.CONFIG.SAB_HOST = headphones.CONFIG.SAB_HOST[0:len(headphones.CONFIG.SAB_HOST) - 1] url = headphones.CONFIG.SAB_HOST + "/" + "api?" + urllib.urlencode(params) diff --git a/headphones/searcher.py b/headphones/searcher.py index 8aaf1407..89e8f6ed 100644 --- a/headphones/searcher.py +++ b/headphones/searcher.py @@ -287,20 +287,20 @@ def more_filtering(results, album, albumlength, new): # Lossless - ignore results if target size outside bitrate range if headphones.CONFIG.PREFERRED_QUALITY == 3 and albumlength and (headphones.CONFIG.LOSSLESS_BITRATE_FROM or headphones.CONFIG.LOSSLESS_BITRATE_TO): if headphones.CONFIG.LOSSLESS_BITRATE_FROM: - low_size_limit = albumlength/1000 * int(headphones.CONFIG.LOSSLESS_BITRATE_FROM) * 128 + low_size_limit = albumlength / 1000 * int(headphones.CONFIG.LOSSLESS_BITRATE_FROM) * 128 if headphones.CONFIG.LOSSLESS_BITRATE_TO: - high_size_limit = albumlength/1000 * int(headphones.CONFIG.LOSSLESS_BITRATE_TO) * 128 + high_size_limit = albumlength / 1000 * int(headphones.CONFIG.LOSSLESS_BITRATE_TO) * 128 # Preferred Bitrate - ignore results if target size outside % buffer elif headphones.CONFIG.PREFERRED_QUALITY == 2 and headphones.CONFIG.PREFERRED_BITRATE: logger.debug('Target bitrate: %s kbps' % headphones.CONFIG.PREFERRED_BITRATE) if albumlength: - targetsize = albumlength/1000 * int(headphones.CONFIG.PREFERRED_BITRATE) * 128 + targetsize = albumlength / 1000 * int(headphones.CONFIG.PREFERRED_BITRATE) * 128 logger.info('Target size: %s' % helpers.bytes_to_mb(targetsize)) if headphones.CONFIG.PREFERRED_BITRATE_LOW_BUFFER: - low_size_limit = targetsize - (targetsize * int(headphones.CONFIG.PREFERRED_BITRATE_LOW_BUFFER)/100) + low_size_limit = targetsize - (targetsize * int(headphones.CONFIG.PREFERRED_BITRATE_LOW_BUFFER) / 100) if headphones.CONFIG.PREFERRED_BITRATE_HIGH_BUFFER: - high_size_limit = targetsize + (targetsize * int(headphones.CONFIG.PREFERRED_BITRATE_HIGH_BUFFER)/100) + high_size_limit = targetsize + (targetsize * int(headphones.CONFIG.PREFERRED_BITRATE_HIGH_BUFFER) / 100) if headphones.CONFIG.PREFERRED_BITRATE_ALLOW_LOSSLESS: allow_lossless = True @@ -369,7 +369,7 @@ def sort_search_results(resultlist, album, new, albumlength): if headphones.CONFIG.PREFERRED_QUALITY == 2 and headphones.CONFIG.PREFERRED_BITRATE: try: - targetsize = albumlength/1000 * int(headphones.CONFIG.PREFERRED_BITRATE) * 128 + targetsize = albumlength / 1000 * int(headphones.CONFIG.PREFERRED_BITRATE) * 128 if not targetsize: logger.info('No track information for %s - %s. Defaulting to highest quality' % (album['ArtistName'], album['AlbumTitle'])) @@ -1303,7 +1303,7 @@ def searchTorrent(album, new=False, losslessOnly=False, albumlength=None): match_torrents.sort(key=lambda x: int(x.snatched), reverse=True) if gazelleformat.MP3 in search_formats: # sort by size after rounding to nearest 10MB...hacky, but will favor highest quality - match_torrents.sort(key=lambda x: int(10 * round(x.size/1024./1024./10.)), reverse=True) + match_torrents.sort(key=lambda x: int(10 * round(x.size / 1024. / 1024. / 10.)), reverse=True) if search_formats and None not in search_formats: match_torrents.sort(key=lambda x: int(search_formats.index(x.format))) # prefer lossless # if bitrate: diff --git a/headphones/transmission.py b/headphones/transmission.py index a3f947d9..decc026d 100644 --- a/headphones/transmission.py +++ b/headphones/transmission.py @@ -146,7 +146,7 @@ def torrentAction(method, arguments): # Check if it ends in a port number i = host.rfind(':') if i >= 0: - possible_port = host[i+1:] + possible_port = host[i + 1:] try: port = int(possible_port) host = host + "/transmission/rpc" diff --git a/headphones/versioncheck.py b/headphones/versioncheck.py index 0e5cb9d6..29604914 100644 --- a/headphones/versioncheck.py +++ b/headphones/versioncheck.py @@ -26,7 +26,7 @@ from headphones import logger, version, request def runGit(args): if headphones.CONFIG.GIT_PATH: - git_locations = ['"'+headphones.CONFIG.GIT_PATH+'"'] + git_locations = ['"' + headphones.CONFIG.GIT_PATH + '"'] else: git_locations = ['git'] @@ -36,7 +36,7 @@ def runGit(args): output = err = None for cur_git in git_locations: - cmd = cur_git+' '+args + cmd = cur_git + ' ' + args try: logger.debug('Trying to execute: "' + cmd + '" with shell in ' + headphones.PROG_DIR) @@ -181,7 +181,7 @@ def update(): 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.error('Unable to update from git: ' + line) logger.info('Output: ' + str(output)) else: @@ -216,13 +216,13 @@ def update(): # 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("Invalid update data, update failed: "+str(update_dir_contents)) + logger.error("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:] + 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) diff --git a/headphones/webserve.py b/headphones/webserve.py index 6ce895ff..95b1014f 100644 --- a/headphones/webserve.py +++ b/headphones/webserve.py @@ -456,7 +456,7 @@ class WebInterface(object): for albums in have_albums: #Have to skip over manually matched tracks if albums['ArtistName'] and albums['AlbumTitle'] and albums['TrackTitle']: - original_clean = helpers.cleanName(albums['ArtistName']+" "+albums['AlbumTitle']+" "+albums['TrackTitle']) + original_clean = helpers.cleanName(albums['ArtistName'] + " " + albums['AlbumTitle'] + " " + albums['TrackTitle']) # else: # original_clean = None if original_clean == albums['CleanName']: @@ -526,8 +526,8 @@ class WebInterface(object): new_artist_clean = helpers.cleanName(new_artist).lower() existing_album_clean = helpers.cleanName(existing_album).lower() new_album_clean = helpers.cleanName(new_album).lower() - existing_clean_string = existing_artist_clean+" "+existing_album_clean - new_clean_string = new_artist_clean+" "+new_album_clean + existing_clean_string = existing_artist_clean + " " + existing_album_clean + new_clean_string = new_artist_clean + " " + new_album_clean if existing_clean_string != new_clean_string: have_tracks = myDB.action('SELECT Matched, CleanName, Location, BitRate, Format FROM have WHERE ArtistName=? AND AlbumTitle=?', (existing_artist, existing_album)) update_count = 0 @@ -568,7 +568,7 @@ class WebInterface(object): manualalbums = myDB.select('SELECT ArtistName, AlbumTitle, TrackTitle, CleanName, Matched from have') for albums in manualalbums: if albums['ArtistName'] and albums['AlbumTitle'] and albums['TrackTitle']: - original_clean = helpers.cleanName(albums['ArtistName']+" "+albums['AlbumTitle']+" "+albums['TrackTitle']) + original_clean = helpers.cleanName(albums['ArtistName'] + " " + albums['AlbumTitle'] + " " + albums['TrackTitle']) if albums['Matched'] == "Ignored" or albums['Matched'] == "Manual" or albums['CleanName'] != original_clean: if albums['Matched'] == "Ignored": album_status = "Ignored" @@ -600,7 +600,7 @@ class WebInterface(object): update_clean = myDB.select('SELECT ArtistName, AlbumTitle, TrackTitle, CleanName, Matched from have WHERE ArtistName=?', [artist]) update_count = 0 for tracks in update_clean: - original_clean = helpers.cleanName(tracks['ArtistName']+" "+tracks['AlbumTitle']+" "+tracks['TrackTitle']).lower() + original_clean = helpers.cleanName(tracks['ArtistName'] + " " + tracks['AlbumTitle'] + " " + tracks['TrackTitle']).lower() album = tracks['AlbumTitle'] track_title = tracks['TrackTitle'] if tracks['CleanName'] != original_clean: @@ -618,7 +618,7 @@ class WebInterface(object): update_clean = myDB.select('SELECT ArtistName, AlbumTitle, TrackTitle, CleanName, Matched from have WHERE ArtistName=? AND AlbumTitle=?', (artist, album)) update_count = 0 for tracks in update_clean: - original_clean = helpers.cleanName(tracks['ArtistName']+" "+tracks['AlbumTitle']+" "+tracks['TrackTitle']).lower() + original_clean = helpers.cleanName(tracks['ArtistName'] + " " + tracks['AlbumTitle'] + " " + tracks['TrackTitle']).lower() track_title = tracks['TrackTitle'] if tracks['CleanName'] != original_clean: album_id_check = myDB.action('SELECT AlbumID from tracks WHERE CleanName=?', [tracks['CleanName']]).fetchone() @@ -764,7 +764,7 @@ class WebInterface(object): sortcolumn = 1 filtered.sort(key=lambda x: x[sortcolumn], reverse=sSortDir_0 == "desc") - rows = filtered[iDisplayStart:(iDisplayStart+iDisplayLength)] + rows = filtered[iDisplayStart:(iDisplayStart + iDisplayLength)] rows = [[row[0], row[2], row[1]] for row in rows] return json.dumps({ @@ -800,14 +800,14 @@ class WebInterface(object): totalcount = myDB.select('SELECT COUNT(*) from artists')[0][0] if sortbyhavepercent: - filtered.sort(key=lambda x: (float(x['HaveTracks'])/x['TotalTracks'] if x['TotalTracks'] > 0 else 0.0, x['HaveTracks'] if x['HaveTracks'] else 0.0), reverse=sSortDir_0 == "asc") + filtered.sort(key=lambda x: (float(x['HaveTracks']) / x['TotalTracks'] if x['TotalTracks'] > 0 else 0.0, x['HaveTracks'] if x['HaveTracks'] else 0.0), reverse=sSortDir_0 == "asc") #can't figure out how to change the datatables default sorting order when its using an ajax datasource so ill #just reverse it here and the first click on the "Latest Album" header will sort by descending release date if sortcolumn == 'ReleaseDate': filtered.reverse() - artists = filtered[iDisplayStart:(iDisplayStart+iDisplayLength)] + artists = filtered[iDisplayStart:(iDisplayStart + iDisplayLength)] rows = [] for artist in artists: row = {"ArtistID": artist['ArtistID'], @@ -1357,7 +1357,7 @@ class WebInterface(object): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" tweet = notifiers.TwitterNotifier() result = tweet._get_credentials(key) - logger.info(u"result: "+str(result)) + logger.info(u"result: " + str(result)) if result: return "Key verification successful" else: