#!/usr/bin/python

# cpm3u
#
# Copy the files referenced by a m3u file to a directory.
#
# 2006 Simeon Veldstra <reallifesim@gmail.com>
# Free to use and distribute. No warranty.

import sys, os, os.path, shutil

class Error(Exception):
	def __init__(self, msg):
		self.msg = msg
	def __str__(self):
		return self.msg

def cpm3u(fname, dest):
	"""Copy the files."""
	if not os.path.exists(fname):
		raise Error, "%s is not a valid m3u file." % fname
	if not os.path.isdir(dest):
		raise Error, "%s is not a valid directory path." % dest

	try:
		fp = open(fname, 'r')
		lines = fp.readlines()
		fp.close()
	except IOError:
		raise Error, "IO Error reading playlist."
	
	for line in lines:
		path = line[:-1]

		if path.startswith('/'):
			if os.path.exists(path):
				print "Copying %s" % path
				shutil.copy(path, dest)
			else:
				sys.stderr.write("File: %s Not found." % path)

		elif path.startswith('http://'):
			oldpwd = os.getcwd()
			os.chdir(dest)
			print "Downloading URL %s" % path
			os.system('wget "%s"' % path) 
			os.chdir(oldpwd)
			
			
def main():
	if len(sys.argv) == 3:
		fname = sys.argv[1]
		dest = sys.argv[2]
	else:
		print "Useage: cpm3u playlist dest_dir"
		sys.exit(1)
	try:
		cpm3u(fname, dest)
	except Error, txt:
		print txt
	
if __name__ == "__main__": main()

