import os import re import cPickle as pickle from libdata import LibData #from song import Song class Library(): def __init__(self,prnt): #def __init__(self): self.prnt = prnt self.data = LibData() self.goodTypes = ["ogg","mp3","wma"] # Build up directory if library save self.save = os.path.expanduser("~") self.save = os.path.join(self.save,".ocarina") self.save = os.path.join(self.save,"library.pickle") # Load existing library if os.path.exists(self.save): self.prnt(["Library found, loading..."]) p = pickle.Unpickler(open(self.save)) self.data = p.load() # Begin a scan on dir def scan(self,dir): self.data = LibData() self.data.path = os.path.expanduser(dir) self.prnt(["Scanning: "+self.data.path]) self.traverse("") num = len(self.data.files) self.prnt(["Found "+str(num)+" files!"]) self.dump() # Traverse directorys def traverse(self,dir): # List and sort contents contents = os.listdir(os.path.join(self.data.path,dir)) contents.sort() for entry in contents: joined = os.path.join(dir,entry) full = os.path.join(self.data.path,joined) # Call traverse on directorys if os.path.isdir(full): self.traverse(joined) # Add music to library else: tSplit = entry.rsplit('.') type = tSplit[len(tSplit)-1].lower() if (type in self.goodTypes) == True: self.hash(joined) # Hash a file and add to library def hash(self,file): index = len(self.data.files) self.data.files+=[file] file = file.lower() # Only keep letters and numbers words = re.sub('[^a-z0-9]',' ',file).split() for word in words: if (word in self.data.map.keys()) == True: self.data.map[word]+=[index] else: self.data.map[word] = [index] # Dump to file def dump(self): out = open(self.save,'w') p = pickle.Pickler(out,2) p.dump(self.data) out.close()