"""----------------------------------------------------------------------------\
|                     PodCast Recent Playlist Generator		                  |
|-----------------------------------------------------------------------------|
|                         Created by Jason Darrow           	              |
|                  		(http://www.jasondarrow.com) 		                  |
|-----------------------------------------------------------------------------|
| A utility that searches through existing podcast Playlist directories in    |
| order to find recent mp3 file.  One a file is found that is less than or    |
|  equal to 3 days it is copied to the "RECENT PODCASTS" playlist.            | 
|                                                                             |
|  AUTHOR'S NOTE: I use this in with http://www.dopplerradio.net/ to          |
|  automatically download podcasts via RSS feeds.  I then setup Windows Media |
|  Player with PlayLists and synchronize those directories created by         |
|  Doppler to my MP3 player.												  |
|  References:  http://www.wmplugins.com/EditorsCorner/Editors.aspx			  |
|  http://www.engadget.com/2004/10/12/how-to-getting-podcasts-                |
|  on-a-portable-media-center-and-other/									  |
|-----------------------------------------------------------------------------|
|                  Copyright (c) 2006 Jason Darrow			                  |
|-----------------------------------------------------------------------------|
| This software is provided "as is", without warranty of any kind, express or |
| implied, including  but not limited  to the warranties of  merchantability, |
| fitness for a particular purpose and noninfringement. In no event shall the |
| authors or  copyright  holders be  liable for any claim,  damages or  other |
| liability, whether  in an  action of  contract, tort  or otherwise, arising |
| from,  out of  or in  connection with  the software or  the  use  or  other |
| dealings in the software.                                                   |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| GPL - The GNU General Public License    http://www.gnu.org/licenses/gpl.txt |
| Permits anyone the right to use and modify the software without limitations |
| as long as proper  credits are given  and the original  and modified source |
| code are included. Requires  that the final product, software derivate from |
| the original  source or any  software  utilizing a GPL  component, such  as |
| this, is also licensed under the GPL license.                               |
|-----------------------------------------------------------------------------|
| 2006-03-25 | First version                                                  |
|-----------------------------------------------------------------------------|
"""

import os
import stat
import time
import fnmatch
import re
import time
import datetime
import shutil


class FileGetter:
	
	topDirectory = 'C:/PODCASTS/new_podcasts/'
	recentPodcastDirectoryName = 'RECENT_PODCASTS'
	newMp3FileList = []
	recentPodcastsDirectionary=[]
	existingDirectoryDirectionary={}
	fileAge = 3

	"""
    	Create a list that contains references to all podcast directories
    """
	def topLevelDirectoryGetter(self):
		directoryList = []
		
		for fileName in os.listdir ( FileGetter.topDirectory ):
			fileStats = os.stat ( self.topDirectory + fileName )
			if fileName == 'RECENT_PODCASTS':
				continue
			if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ):
				directoryList.append(fileName)
				
		return directoryList
	    
	"""
    	Create a list that contains references to all podcasts (mp3 files)
    """	
	def individualFileNameGet(self, directory):
		list = []
		filePattern = fnmatch.translate ( '*.mp3' )
		mp3Directory = FileGetter.topDirectory + directory
		for fileName in os.listdir ( mp3Directory ):
			if re.match ( filePattern, fileName ):
				list.append(fileName)
				
		return list
	
	"""
    	Create a directionary to contain existing playlist directories and files within
    """	
	def makeFileDictionary(self):
		list = self.topLevelDirectoryGetter()
		for fileName in list:
			self.existingDirectoryDirectionary[fileName] = self.individualFileNameGet(fileName)
			
	"""
    	Search for existing files and assign those under the file age to the 
    	recentPodcastsDirectionary dictionary
    """		
	def parseExistingMp3Files(self):
		self.makeFileDictionary()
		for Mp3Directory, Mp3FileList in self.existingDirectoryDirectionary.items():
			newFileList = []
			for Mp3File in Mp3FileList:
				fileStats = os.stat ( self.topDirectory + Mp3Directory + '/' + Mp3File )
				creationDateOfFile = datetime.datetime.fromtimestamp(fileStats [ stat.ST_CTIME ])
				if self.decideToAddToNewList(creationDateOfFile):
					"""Delimiter and list seems lame to me but it works"""
					self.recentPodcastsDirectionary.append(Mp3Directory + '~|~' + Mp3File)

					
	"""
    	If the file is older then 3 days return False and it be added to the List 
		( re-reading seems odd but it works?)
    """	
	def decideToAddToNewList(self, time):
		difference = datetime.datetime.today() - time
		if difference.days >= self.fileAge:
			return False
		else:
			return True
		
	"""
		Remove existing directory and create new to prepare for new files
    """				
	def removeAndCreateDirectory(self):
		newPodcastDirectory = self.topDirectory + self.recentPodcastDirectoryName
		try:
			shutil.rmtree( newPodcastDirectory )
		except OSError:
			print "[Errno 2] No such file or directory can be deleted: " + newPodcastDirectory
			
		os.mkdir ( newPodcastDirectory )
		
	"""
		Copy mp3 files to new directory
    """		
	def moveNewMp3Files(self):
		for Mp3File in self.recentPodcastsDirectionary:
			tempList = Mp3File.split('~|~')
			sourceMp3Directory = tempList[0]
			sourceMp3File = tempList[1]
			sourceFile = self.topDirectory + sourceMp3Directory + '/' + sourceMp3File
			destFile = self.topDirectory + self.recentPodcastDirectoryName + '/' + sourceMp3File
			shutil.copy(sourceFile, destFile)

	"""
		Helper Method to run this class
    """			
	def moveRecentMp3FilesToPlayList(self):
		self.parseExistingMp3Files()
		self.removeAndCreateDirectory()
		self.moveNewMp3Files()
		
		
mainDirectories = FileGetter()
mainDirectories.moveRecentMp3FilesToPlayList()


	