diff --git a/fresh.py b/fresh.py index 024f6ed..a45d0cc 100644 --- a/fresh.py +++ b/fresh.py @@ -3,6 +3,7 @@ import sys import os import json +import logging import webbrowser import textwrap import spotipy @@ -13,6 +14,22 @@ from models import User import cutie +# Adding formatter for the logger +formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') +# Adding file handler to write logs to file +fresh_fh = logging.FileHandler('fresh.log') +fresh_fh.setLevel(logging.DEBUG) +fresh_fh.setFormatter(formatter) +# Adding console handler to write logs to console as well +fresh_ch = logging.StreamHandler() +fresh_ch.setLevel(logging.ERROR) +fresh_ch.setFormatter(formatter) +# Initiating a logger object and adding all handlers to it +logger = logging.getLogger('fresh_logs') +logger.setLevel(logging.DEBUG) +logger.addHandler(fresh_fh) +logger.addHandler(fresh_ch) + def createUserConfig(user, config_path='.config.ini'): """ Create .config.ini file for Spotify credentials. @@ -90,7 +107,7 @@ def createUser(): p_credentials['client_secret']) elif not os.path.isfile('.config.ini'): - print('Credentials file not found!') + logger.debug('Credentials file not found!') # get credentials s_client_id = input('Enter your Spotify Client ID: ').strip() @@ -128,7 +145,7 @@ def createUser(): config['soundcloud'] = {} ''' except Exception as e: - print(f'config failure: {e}') + logger.error(f'config failure: {e}') return user @@ -313,20 +330,20 @@ def process_subreddit(subreddit, choice, l): elif choice.lower() == 'top': sub_choice = subreddit.top(limit=l) else: - print("Unsupported sorting method") + logger.error("Unsupported sorting method") sys.exit() return sub_choice -def addSpotifyTrack(fresh, threshold, includeAlbums, verbose, sub, tracks): +def addSpotifyTrack(spotifyObj, fresh, threshold, includeAlbums, verbose, sub, tracks): # check if post is a track or album isMatch = re.search('(track|album)', sub.url) if isMatch != None: if verbose: - print("Post: ", sub.title) - print("URL: ", sub.url) - print("Score: ", sub.score) - print("------------------------\n") + logger.debug("Post: {}".format(sub.title)) + logger.debug("URL: {}".format(sub.url)) + logger.debug("Score: {}".format(sub.score)) + logger.debug("------------------------\n") # Discard post below threshold if given if threshold and sub.score < threshold: @@ -390,7 +407,7 @@ def main(): tracks_array = [] for sub in sub_choice: if sub.domain == "open.spotify.com": - addSpotifyTrack(fresh, threshold, includeAlbums, verbose, sub, tracks) + addSpotifyTrack(spotifyObj, fresh, threshold, includeAlbums, verbose, sub, tracks) else: title, tags = filter_tags(sub.title) @@ -407,10 +424,10 @@ def main(): otherDomainList = ['youtu.be', 'youtube.com', 'soundcloud.com'] # handle non-spotify posts if sub.domain in otherDomainList and verbose: - print("Post: ", sub.title) - print("URL: ", sub.url) - print("Score: ", sub.score) - print("------------------------\n") + logger.debug("Post: {}".format(sub.title)) + logger.debug("URL: {}".format(sub.url)) + logger.debug("Score: {}".format(sub.score)) + logger.debug("------------------------\n") tracks.append(track_url) # handle overflow @@ -424,6 +441,7 @@ def main(): # handle remove duplicates of tracks before adding new tracks if tracks != [] or tracks_array != []: try: + results = [] if len(tracks_array) >= 1: for tr in tracks_array: for playlist in user.playlists: @@ -435,14 +453,14 @@ def main(): results = spotifyObj.user_playlist_add_tracks( user.username, playlist, tr) if verbose: - 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'])) + logger.info('New Tracks added to {}'.format((spotifyObj.user_playlist(user.username, playlist, 'name')['name'], ': ', abs( + existing_tracks['total'] - spotifyObj.user_playlist_tracks(user.username, playlist)['total'])))) print() except: if results == [] and verbose: - print("No new tracks have been added.") + logger.info("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) diff --git a/models.py b/models.py index e669ad0..a6e4f34 100644 --- a/models.py +++ b/models.py @@ -1,6 +1,7 @@ import spotipy import spotipy.util as util import argparse +import logging import crontab from crontab import CronTab import textwrap @@ -8,6 +9,22 @@ # user object to hold the things class User: + # Adding formatter for the logger + formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') + # Adding file handler to write logs to file + fresh_fh = logging.FileHandler('fresh.log') + fresh_fh.setLevel(logging.DEBUG) + fresh_fh.setFormatter(formatter) + # Adding console handler to write logs to console as well + fresh_ch = logging.StreamHandler() + fresh_ch.setLevel(logging.ERROR) + fresh_ch.setFormatter(formatter) + # Initiating a logger object and adding all handlers to it + logger = logging.getLogger('fresh_logs') + logger.setLevel(logging.DEBUG) + logger.addHandler(fresh_fh) + logger.addHandler(fresh_ch) + def __init__(self, username, client_id, client_secret, redirect, playlists): self.username = username self.client_id = client_id @@ -44,7 +61,7 @@ def addPlaylists(self): try: ownedPlaylists = self.fetchPlaylists(offset) except: - print("You don't have any Spotify playlists!") + User.logger.info("You don't have any Spotify playlists!") return self.printOwnedPlaylists(ownedPlaylists) enteringPlaylists = True @@ -67,7 +84,7 @@ def addPlaylists(self): ownedPlaylists = self.fetchPlaylists(offset) except: print() - print("No more playlists to view.") + User.logger.info("No more playlists to view.") offset = offset - 50 finally: self.printOwnedPlaylists(ownedPlaylists) @@ -77,7 +94,7 @@ def addPlaylists(self): ownedPlaylists = self.fetchPlaylists(offset) except: print() - print("No previous playlists to view.") + User.logger.info("No previous playlists to view.") offset = offset + 50 finally: self.printOwnedPlaylists(ownedPlaylists) @@ -89,7 +106,7 @@ def addPlaylists(self): print("Unexpected input!") continue except: - print("That playlist number doesn't exist!") + User.logger.error("That playlist number doesn't exist!") enteringPlaylists = self.str2bool(input('Would you like to enter another playlist ID? [Y/N] ').strip()) self.playlists.extend(playlistsToAdd) @@ -111,8 +128,8 @@ def printOwnedPlaylists(self, ownedPlaylists): else: for i, playlist in enumerate(ownedPlaylists): print() - print(f"{i+1}. {playlist['name']}") - print(' total tracks', playlist['tracks']['total']) + User.logger.debug(f"{i+1}. {playlist['name']}") + User.logger.debug(' total tracks {}'.format(playlist['tracks']['total'])) # prompt user to remove current playlists def removePlaylists(self): @@ -124,15 +141,15 @@ def removePlaylists(self): index = int(index) del self.playlists[index-1] except: - print("That playlist number doesn't exist!") + User.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:") + User.logger.info("\nYour current playlists are:") for index, playlist in enumerate(self.playlists): - print(f"{index+1}. {sp.user_playlist(self.username, playlist, 'name')['name']}") + User.logger.debug(f"{index+1}. {sp.user_playlist(self.username, playlist, 'name')['name']}") print() # use python-crontab to write a cron task