##########################################################################################
#Copyright (c) 2007, Leblanc Simon <contact@leblanc-simon.eu>
#
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without modification, 
#are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright notice, 
#      this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright notice, 
#      this list of conditions and the following disclaimer in the documentation 
#      and/or other materials provided with the distribution.
#    * Neither the name of the Leblanc Simon nor the names of its contributors 
#      may be used to endorse or promote products derived from this software without
#      specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
#CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
#EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###########################################################################################

#!/usr/bin/env python

import os.path
import sys
import glob
import string
import mutagen
from mutagen import id3
import mutagen.oggvorbis
from mutagen.easyid3 import EasyID3

#####################################
#
#	Class Ogg2MP3
#
#####################################
class Ogg2MP3:
	__fileOgg	= ""
	__fileMP3	= ""
	__delete	= 0
	__infos		= {}
	__infoAdd	= ["album", "artist", "title"]
	
	def __init__(self, filename = ""):
		if self.load(filename, self.__delete) == -1:
			return 0


	def load(self, filename, delete = 0):
		"""
		Re-initialise les variables et charge un fichier dans la classe
		"""
		self.__fileOgg	= ""
		self.__fileMP3	= ""
		self.__delete	= 0
		self.__infos	= {}
		
		if filename == "":
			return 0
		
		if os.path.exists(filename) == 0 | os.path.isfile(filename) == 0:
			return -1
		
		if delete != 0 | delete != 1:
			return -1
			
		self.__fileOgg	= filename
		self.__delete	= delete
		return 1


	def save(self):
		"""
		Sauvegarde le fichier en MP3 et supprime le Ogg si neccesaire
		"""
		if self.__getInfo() == 0:
			return "Error in the method: __getInfo(self)"
		
		if self.__setNameMP3() == 0:
			return "Error in the method: __setNameMP3(self)"
		
		if self.__oggToMP3() == 0:
			return "Error in the method: __oggToMP3(self)"
		
		if self.__setInfoMP3() == 0:
			return "Error in the method: __setInfoMP3(self)"
		
		if self.__delete == 1:
			self.__deleteFile()
		
		return "The file " + self.__fileOgg + " is converted in MP3"
	
	
	def __getInfo(self):
		"""
		Recupere les informations du fichier ogg
		"""
		if self.__fileOgg == "":
			return 0
		
		self.__infos = mutagen.oggvorbis.Open(self.__fileOgg)
		return 1


	def __setInfoMP3(self):
		"""
		Ajoute les informations au MP3
		"""
		if self.__fileMP3 == "":
			return 0
		
		mp3file = EasyID3(self.__fileMP3)
		for item in self.__infoAdd:
			mp3file[item] = self.__infos[item]
		
		mp3file.save()
		return 1
		

	def __oggToMP3(self):
		"""
		Transforme le fichier en MP3
		"""
		if self.__fileMP3 == "":
			return 0
		
		if os.name == "nt":
			os.system("oggdec.exe --quiet -o - \"" + self.__fileOgg + "\" | lame.exe --add-id3v2 --quiet --tc \"Encoded by QOgg2mp3\" -h - > \"" + self.__fileMP3 + "\"")
			return 1
		elif os.name == "posix":
			os.system("oggdec --quiet -o - \"" + self.__fileOgg + "\" | lame --add-id3v2 --quiet --tc \"Encoded by QOgg2mp3\" -h - > \"" + self.__fileMP3 + "\"")
			return 1
		else:
			return 0


	def __setNameMP3(self):
		"""
		Donne le nom du fichier MP3
		"""
		self.__fileMP3 = self.__fileOgg
	
		self.__fileMP3 = string.replace(self.__fileMP3, ".ogg", ".mp3")
		self.__fileMP3 = string.replace(self.__fileMP3, ".Ogg", ".mp3")
		self.__fileMP3 = string.replace(self.__fileMP3, ".OGG", ".mp3")


	def __deleteFile(self):
		"""
		Supprime le fichier source (Ogg)
		"""
		os.remove(self.__fileOgg)


################################
#
#	Function
#
################################
def getArgs():
	if len(sys.argv) != 2:
		print "Usage: "+sys.argv[0]+" directory"
		exit (-1)
	
	dirname = sys.argv[1]
	if dirname[len(dirname) - 1] != "/":
		dirname += "/"
	
	if os.path.exists(dirname):
		return dirname
	else:
		print "The directory '" + dirname + "' doesn't exist"
		exit(-2)


################################
#
# 	MAIN
#
################################
dirname = getArgs()

liste = glob.glob(dirname + "*.ogg")
liste.sort()
ogg = Ogg2MP3()
for filename in liste:
	ogg.load(filename, 1)
	print ogg.save()

print "Operation terminee"
exit(0)
