diff --git a/app.py b/app.py index 9faca76..1538d09 100644 --- a/app.py +++ b/app.py @@ -3,9 +3,19 @@ from models import RedditData import spotipy import prawcore +import logging from xml.sax import saxutils as su +# Setting up logger +logging.basicConfig( + filename='fresh_script.log', + filemode='w+', + format='%(name)s - %(levelname)s - %(message)s' +) +logger = logging.getLogger(__name__) + + # global objects app = Flask(__name__) User = createUser() @@ -43,6 +53,7 @@ def tracks(Name=None): media = sub.media_embed images.append(su.unescape(media['content'])) print("spotify media:", media) + logger.info("spotify media:", media) else: # handle non-spotify posts @@ -62,14 +73,17 @@ def tracks(Name=None): media = sub.media_embed print("other media:", media) + logger.info("other media:", media) if 'content' in media: s = su.unescape(media['content']) images.append(s) print("content media:", s) + logger.info("content media:", s) else: images.append(media) print("other media:", media) + logger.info("other media:", media) # zip tracks and info together to be rendered on the tracks page track_info = zip(titles, tracks, images) diff --git a/fresh.py b/fresh.py index 024f6ed..e72134b 100644 --- a/fresh.py +++ b/fresh.py @@ -12,6 +12,11 @@ from constants import ft_set from models import User import cutie +import logger + +# Getting logger +logger = logging.getLogger(__name__) + def createUserConfig(user, config_path='.config.ini'): """ @@ -91,6 +96,7 @@ def createUser(): elif not os.path.isfile('.config.ini'): print('Credentials file not found!') + logger.info('Credentials file not found!') # get credentials s_client_id = input('Enter your Spotify Client ID: ').strip() @@ -129,6 +135,7 @@ def createUser(): ''' except Exception as e: print(f'config failure: {e}') + logger.error(f'config failure: {e}') return user @@ -314,6 +321,7 @@ def process_subreddit(subreddit, choice, l): sub_choice = subreddit.top(limit=l) else: print("Unsupported sorting method") + logger.warn("Unsupported sorting method") sys.exit() return sub_choice @@ -328,6 +336,10 @@ def addSpotifyTrack(fresh, threshold, includeAlbums, verbose, sub, tracks): print("Score: ", sub.score) print("------------------------\n") + logger.info("Post: ", sub.title) + logger.info("URL: ", sub.url) + logger.info("Score: ", sub.score) + # Discard post below threshold if given if threshold and sub.score < threshold: return @@ -382,6 +394,7 @@ def main(): spotifyObj.trace = False if args.verbose: print('Welcome to the HipHopHeads Fresh Script') + logger.info('Welcome to the HipHopHeads Fresh Script') verbose, l, choice, threshold, includeAlbums, fresh = process_args( args, user) sub_choice = process_subreddit(subreddit, choice, l) @@ -412,6 +425,10 @@ def main(): print("Score: ", sub.score) print("------------------------\n") + logger.info("Post: ", sub.title) + logger.info("URL: ", sub.url) + logger.info("Score: ", sub.score) + tracks.append(track_url) # handle overflow if len(tracks) > 90: @@ -438,13 +455,18 @@ def main(): print('New Tracks added to ', spotifyObj.user_playlist(user.username, playlist, 'name')['name'], ': ', abs( existing_tracks['total'] - spotifyObj.user_playlist_tracks(user.username, playlist)['total'])) print() + logger.info('New Tracks added to ', spotifyObj.user_playlist(user.username, playlist, 'name')['name'], ': ', abs( + existing_tracks['total'] - spotifyObj.user_playlist_tracks(user.username, playlist)['total'])) except: if results == [] and verbose: print("No new tracks have been added.") + logger.error("No new tracks have been added.") else: print("An error has occured removing or adding new tracks") + logger.error("An error has occured removing or adding new tracks") # if verbose: # print(tracks) + # logger.error(tracks) if __name__ == '__main__': main() diff --git a/models.py b/models.py index e669ad0..e6347a3 100644 --- a/models.py +++ b/models.py @@ -5,6 +5,11 @@ from crontab import CronTab import textwrap import praw +import logging + +# Getting logger +logger = logging.getLogger(__name__) + # user object to hold the things class User: @@ -45,6 +50,7 @@ def addPlaylists(self): ownedPlaylists = self.fetchPlaylists(offset) except: print("You don't have any Spotify playlists!") + logger.error("You don't have any Spotify playlists!") return self.printOwnedPlaylists(ownedPlaylists) enteringPlaylists = True @@ -68,6 +74,7 @@ def addPlaylists(self): except: print() print("No more playlists to view.") + logger.error("No more playlists to view.") offset = offset - 50 finally: self.printOwnedPlaylists(ownedPlaylists) @@ -78,6 +85,7 @@ def addPlaylists(self): except: print() print("No previous playlists to view.") + logger.error("No previous playlists to view.") offset = offset + 50 finally: self.printOwnedPlaylists(ownedPlaylists) @@ -87,9 +95,11 @@ def addPlaylists(self): else: print() print("Unexpected input!") + logger.error("Unexpected input!") continue except: - print("That playlist number doesn't exist!") + print("That playlist number doesn't exist!")' + logger.error("Unexpected input!")' enteringPlaylists = self.str2bool(input('Would you like to enter another playlist ID? [Y/N] ').strip()) self.playlists.extend(playlistsToAdd) @@ -108,11 +118,14 @@ def printOwnedPlaylists(self, ownedPlaylists): if len(ownedPlaylists) == 0: print() print("You do not own any playlists in this batch. Type 'n' or 'next' to go to the next one.") + logger.warn("You do not own any playlists in this batch. Type 'n' or 'next' to go to the next one.") else: for i, playlist in enumerate(ownedPlaylists): print() print(f"{i+1}. {playlist['name']}") print(' total tracks', playlist['tracks']['total']) + logger.info(f"{i+1}. {playlist['name']}") + logger.info(' total tracks', playlist['tracks']['total']) # prompt user to remove current playlists def removePlaylists(self): @@ -125,14 +138,17 @@ def removePlaylists(self): del self.playlists[index-1] except: print("That playlist number doesn't exist!") + logger.error("That playlist number doesn't exist!") removingPlaylists = self.str2bool(input('Would you like to remove another playlist? [Y/N] ').strip()) # print out numbered list of the names of the playlists that are currently being added to def printPlaylists(self): sp = spotipy.Spotify(auth=self.token) print("\nYour current playlists are:") + logger.info(Your current playlists are:") for index, playlist in enumerate(self.playlists): print(f"{index+1}. {sp.user_playlist(self.username, playlist, 'name')['name']}") + logger.info(f"{index+1}. {sp.user_playlist(self.username, playlist, 'name')['name']}") print() # use python-crontab to write a cron task