Skip to content
Snippets Groups Projects
Commit 17add0d0 authored by hdd29's avatar hdd29
Browse files

technically has all functions within 1 file cddb

parent ef80bb1d
Branches
No related tags found
No related merge requests found
#!/usr/bin/env python3
import sys
import argparse
import os
#from . import classDef
#from classDef import Album
class Album():
def __init__(self):
self.name = 0
self.artist = 0
self.songs = []
self.date = 0
def addSong(self, song):
self.songs.append(song)
def __str__(self):
string = str(self.artist) + '\n'
string += f'{self.date} {self.name}\n'
for song in self.songs:
string += f'-{song}\n'
string+= '\n'
return string
def __eq__(self, other):
name = (self.name == other.name)
artist = (self.artist == other.artist)
date = (self.date ==other.date)
return (name and artist and date)
def getFirstNonEmpty(stringList):
for i in range(0,len(stringList)):
if not stringList[i]=='':
return i
cd = open(f"{os.getenv('CDDB', 'CDDB not found' )}", 'r')
cd.seek(0)
#Clean up list of lines from CDDB and get list of index of blank lines
lineList=cd.readlines()
count = 0
for line in lineList:
lineList[count]=line.rstrip('\n')
count += 1
beginLineInd = getFirstNonEmpty(lineList)
inBlank = [beginLineInd-1]
count = beginLineInd
for line in lineList[beginLineInd::]:
if not lineList[count]:
inBlank.append(count)
count += 1
inBlank.append(len(lineList))
albumDict = {}
for i in inBlank[::-1]:
if lineList[i-1] == '':
inBlank.pop(inBlank.index(i))
lineList.pop(i-1)
#print(f'updated inBlank: {inBlank}')
#Iterate through list of index of blank lines and store info in album class data structure
count = 0
for index in inBlank[0:-1]:
album = Album()
album.artist=lineList[index+1]
yearName = lineList[index+2].split()
album.date = yearName[0]
album.name = ' '.join(yearName[1::])
start = index + 3
end = inBlank[count + 1]
for song in lineList[start:end]:
album.addSong(song.lstrip('-'))
if album.artist not in albumDict.keys():
albumDict[album.artist] = [album]
else:
albumDict[album.artist].append(album)
count += 1
#for artist in albumDict.keys():
# for album in albumDict[artist]:
# print(album)
for artist in albumDict.keys():
albumDict[artist] = sorted(albumDict[artist], key=lambda album: album.date)
cd.close()
#The list operation: call up listAlbums, which depends on artistMenu
def artistMenu(albumDict, purpose):
print('Here are the artists: \n')
enum = 1
artistList = []
for artist in albumDict.keys():
print(f'{enum}. {artist} ')
enum += 1
artistList.append(artist)
enum = 0
err = True
while err:
artistChosen = input(f'Enter a number to choose the corresponding artist for {purpose} as listed above, \n or press "q" to quit\n')
if str(artistChosen) == 'q':
err = False
return 0
else:
numchosen = -1
try:
numchosen = int(artistChosen)
if numchosen < (len(albumDict.keys())+1) and numchosen > 0 :
err = False
return artistList[numchosen - 1] #name of artist chosen
else:
print(f'Invalid input: Please enter an integer between 1 and {len(albumDict.keys())}')
except ValueError:
print(f'Invalid input: Please enter an integer between 1 and {len(albumDict.keys())}')
#elif isinstance(artistChosen, int):
#if artistChosen < (len(albumDict.keys())+1) and artistChosen > 0 :
#err = False
#return artistList[int(artistChosen) - 1] #name of artist chosen
#else:
#print(f'Invalid input: Please enter an integer between 1 and {len(albumDict.keys())}')
def listAlbums(res, albumDict, purpose):
albumList = sorted(albumDict[res], key=lambda album: album.date) #sorted list of albums by artist chosen
enum = 0
for album in albumList:
enum += 1
print(f'{enum}. {album.name}')
enum = 0
err = True
while err:
albumchosen = input(f'Enter a number to choose the corresponding album as listed above for {purpose}, \n \or press "a" to return to the artist menu\n')
if str(albumchosen) == 'a':
err = False
return 0
else:
numchosen = -1
try:
numchosen = int(albumchosen)
if numchosen <(len(albumList) + 1) and numchosen > 0:
err=False
return albumchosen
else:
print(f'Invalid input: Please enter an integer between 1 and {len(albumList)})')
except ValueError:
print(f'Invalid input: Your input is not an integer. Please enter an integer between 1 and +{len(albumList)})')
# if str(albumchosen) != 'a': #used to be == a
# if isinstance(albumchosen, int):
# if albumchosen < (len(albumList)+1) and albumchosen > 0 :
# err = False
# return albumchosen #res is the string of name of artistchosen
# else:
# print(f'Invalid input: please enter an interger between 1 and {len(albumList)}')
# else:
# print(f'Invalid input: Your input is not an integer. Please enter an integer between 1 and {len(albumList)})')
# else:
# err = False
# return 0
def lUti(albumDict):
albumchosen = 0
while albumchosen == 0:
artistchosen = artistMenu(albumDict, 'listing')
#albumList = sorted(albumDict[artistchosen], key=lambda album: album.date)
if artistchosen == 0:
sys.exit()
albumchosen = listAlbums(artistchosen, albumDict, 'song listing')
while True:
albumList = sorted(albumDict[artistchosen], key=lambda album:album.date)
for song in albumList[int(albumchosen)-1].songs:
print(song)
res3 = input(str('Return to the previous (the album) menu or quit? (press any key = return, 0 = quit)\n'))
if res3 == '0': ########EXIT HERE!!!!!! REMEMBER TO CHECK AGAIN
sys.exit()
else: ################### res3 invalid key
albumchosen = listAlbums(artistchosen, albumDict, 'song listing')
while albumchosen == 0:
artistchosen= artistMenu(albumDict, 'listing')
if artistchosen == 0:
sys.exit()
albumchosen = listAlbums(artistchosen, albumDict, 'song listing')
#the Delete function
def delete(albumDict):
albumchosen = 0
while albumchosen == 0:
artistchosen=artistMenu(albumDict, 'album deletion')
if artistchosen == 0:
sys.exit()
else:
#albumList = sorted(albumDict[artistchosen], key=lambda album:album.date)
albumchosen = listAlbums(artistchosen, albumDict, 'album deletion')
del albumDict[artistchosen][int(albumchosen) -1]
#for k in albumDict.keys():
#for album in albumDict[k]:
#print(album)
def add(albumDict):
new = Album()
new.artist = input("Enter the album's performer: ")
new.name = input("Enter the album's name: ")
new.date = input("Enter year of release: ")
artistExisted = False
for artist in albumDict.keys():
if new.artist == artist:
artistExisted = True
if artistExisted:
for album in albumDict[new.artist]:
if new == album:
print('Album already existed in database, addition operation fails')
return 1
albumDict[new.artist] = []
song = 'nothing'
new.songs.append(input('Enter name(s) of track(s) in this album then press Enter after each entry. Enter an empty string to finish\n'))
while song != '':
song = input()
new.songs.append(song)
del new.songs[-1]
albumDict[new.artist].append(new)
#for k in albumDict.keys():
# for album in albumDict[k]:
# print(album)
def helpmsg():
print('usage: parseCDDB.py [-h] -F\n')
print('Purpose: To manage a CD database')
print('F:\t\t\tthe action to do with the database')
print('Available actions:')
print('-l (default) : List information about a specific album in the database')
print('-d : Delete an album from the database')
print('-a : Add an album to the database')
print('-h : Display official help message')
print('PLEASE REFER TO THE -h OPTION FOR OFFICIAL HELP MESSAGE!!!')
def update(albumDict):
temp = open('temp_cddb', 'a')
for key in albumDict.keys():
for album in albumDict[key]:
temp.write(str(album))
temp.close()
with open('temp_cddb', 'r') as temp:
tempLines = temp.readlines()
#with open("{os.getenv('CDDB', 'CDDB not found')}", 'r') as cd:
# cdLine = cd.readlines()
# print(f'cdLine is: {cdLine}')
cd = open(f"{os.getenv('CDDB', 'CDDB not found' )}", 'r')
cd.seek(0)
cdLine = cd.readlines()
cd.close()
#cddb = open(f"{os.getenv('CDDB', 'CDDB not found')}", 'w')
with open("{os.getenv('CDDB', 'CDDB not found' )}", 'w') as cddb:
for line in tempLines:
cddb.write("%s" % line)
with open("temp_old", 'a') as old:
for line in cdLine:
old.write("%s" % line)
#lUti(albumDict)
#add(albumDict)
#update(albumDict)
def main():
parser=argparse.ArgumentParser(description="A command line utility to manage a CD database")
parser.add_argument("-l", '--list', help="List all the songs in an album. Provide 2 step-choosing mechanism: \n 1. to choose the artist, and 2. choose the album to display", action="store_true")
parser.add_argument('-d','--delete', help='Bring you to a menu to choose an album to delete', action="store_true")
parser.add_argument('-a', '--add', help='Add an album to the database', action="store_true")
#parser.add_argument('-h', '--help', help='Display help messages', action='store_true')
args = parser.parse_args()
#Handle many options get called at same time
if args.list:
lUti(albumDict)
elif args.delete:
delete(albumDict)
update(albumDict)
elif args.add:
add(albumDict)
update(albumDict)
else:
helpmsg()
if __name__=="__main__":
main()
.PHONY: clean view
PAGER = cat
clean:
-\rm temp_old
-\rm temp_cddb
-\rm '{os.getenv('\''CDDB'\'', '\''CDDB not found'\'' )}'
view:
$(PAGER) ./cddb
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment