''' vim: ts=8 sw=4 noexpandtab
Author: Rune Hammersland
version: 0.3

Xbox Media Center comes with a script to play an mp3 file at startup
(StartUpMP3). This script will load a playlist if it exists, and if not,
traverse a directory and load all relevant music files. It is intended as a
replacement for StartUpMP3, and enables you to listen to a playlist, or all
music files in a given directory.

Changelog:
2005-05-27 13:10:33 - Rune Hammersland:
    * Added possibility for multiple playlists.
    * Added possibility for multiple music dirs.

'''

import xbmc
import os

# ---------------------------------------- #
# "Configuration"
# ---------------------------------------- #

# Change this to your playlist(s).
# Written like this: ['path\\to\\plist1', 'to\\plist2', 'plist\\3']
playlist_files= ['E:\\Media\\Music\\playlist.m3u', 'F:\\all.m3u']
# Dirs(s) to traverse if playlist does not exist. NB: No trailing slash.
# Written like this: ['path\\to\\dir1', 'to\\dir2', 'dir\\3']
music_dirs = ['E:\\Media\\Music', 'F:\\Media\\Music']
# Shuffle playlist if this var equals 1.
shuffle_files = 1


# ---------------------------------------- #
# Code
# ---------------------------------------- #

# Function for adding files to playlist
def add_files(pl, dirname, names):
    for filename in names:
        if (os.path.isfile(dirname + "\\" + filename)):
            add = 0
            
            # Check extension of file.
            if (filename[-4:] == ".mp3"): add = 1
            if (filename[-4:] == ".ogg"): add = 1
            if (filename[-4:] == ".wav"): add = 1
            if (filename[-5:] == ".flac"): add = 1
            
            # If file is to be added, do it.
            if (add == 1): pl.add(dirname + "\\" + filename)
        elif (os.path.isdir(dirname + "\\" + filename)):
            os.path.walk(dirname + "\\" + filename, add_files, pl)

# Get music playlist from XBMC
plist = xbmc.PlayList(0)
plist.clear()

# Load playlist if it exists
for playlist_file in playlist_files:
    if (os.path.isfile(playlist_file)):
	plist.load(playlist_file)
# Else, find all available music
else:
    for music_dir in music_dirs:
	os.path.walk(music_dir, add_files, plist)

# Do the shuffle!
if (shuffle_files == 1): plist.shuffle()

xbmc.Player().play(plist)
