Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added logging for files #75

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 35 additions & 17 deletions fresh.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import sys
import os
import json
import logging
import webbrowser
import textwrap
import spotipy
Expand All @@ -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.
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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:
Expand All @@ -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)

Expand Down
35 changes: 26 additions & 9 deletions models.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,30 @@
import spotipy
import spotipy.util as util
import argparse
import logging
import crontab
from crontab import CronTab
import textwrap
import praw

# 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
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)

Expand All @@ -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):
Expand All @@ -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
Expand Down