#!/usr/bin/perl
#
# Music.pl
# This is the FrontEnd script to 
# The Perl Streaming Suite. It 
# Grabs song information from 
# The MySQL Database created
# By Register.pl, and displays
# it via the web. When an album
# is selected, it passes the 
# information off to Stream.pl
# which handles the streaming.
#########################################

#
# Modules To Use
#
use DBD::mysql;				# For Talking to the MySQL DB
use CGI;				# For dealing with the web aspect
use CGI::Carp qw(fatalsToBrowser);	# For debugging and niceness

#
# Create the WebPage Object, and Grab Our Input.
#
my $page        = new CGI;
my $Stream      = $page->param("Stream");
my $BandID      = $page->param("BandID");
my $AlbumID     = $page->param("AlbumID");
my $New         = $page->param("New");
my $Artist      = $page->param("Artist");
my $Album       = $page->param("Album");
my $port        = $page->param("port");

#
# Declare The rest of our variables. 
#
my $script	= "/cgi-bin/Music.pl";
my $ServerAddr	= "SERVERADDR";      	


#
# I've carved up the various possible actions
# that the script can take into subroutines. 
# So, based on the input given to the script
# via the webpage, we decide what subroutine we
# should be running.
#
if      ($Stream)       { &Stream; }  
elsif   ($New)          { &New;    } 
elsif   ($BandID)       { &Band;   }
elsif   ($AlbumID)      { &Album;  }
else                    { die "Input was Invalid or Somethin : $! \n";  }

#
# Subroutines Start Here.
#
sub New
{
my $x = 0;
my @Band;
my @BandID;
#
# Connect to DB and grab info
#
$dbh = DBI->connect("DBI:mysql:music","MYSQLUSER","MYSQLPASS") or die "Can't connect to MySQL DB : $!";
$sth = $dbh->prepare("SELECT * FROM Band");
$sth->execute();
while ($ref = $sth->fetchrow_hashref())
	{
	push (@Band, $ref->{'BandName'});
	push (@BandID, $ref->{'BandID'});
	}
#
# Print out list of available Artists.
#
print $page->header('text/html');
print "<html>\n";
print "<head>\n";
print "<title>\n";
print "Artist Listings\n";
print "</title>\n";
print "<script language = \"javascript\"> \n";
print "</script> \n";
print "<body link=\"#0066ff\" alink=\"#0066ff\" vlink=\"#0066ff\" bgcolor=\"#0066FF\" text=\"#FFFFFF\">\n";
print "<h2><b>These are the Artists Available for Streaming</h2></b>\n";
foreach (@Band)
	{
	$band = $_ ;
	$band =~ s/_/ /g;
	print "<br>\n";
	print "<a href=$script?BandID=$BandID[$x]&Artist=$_ 
		onmouseover=\"document.images[$x].src='/img/button2.gif' \; return true\;\" 
                onmouseout=\"document.images[$x].src='/img/button.gif' \; return true\;\"> 
		<img src='/img/button.gif'></a> $band \n";
	$x++;
	}
print $page->end_html;
#
# Disconnect from database;
#
$sth->finish;
$dbh->disconnect;
}


sub Band
{
my @Album;
my @AlbumID;
my $x = 0;
#
# Split out the underscores for Display purposes
#
$Artist =~ s/_/ /g;
#
# Connect to the DB and grab info
#
$dbh = DBI->connect("DBI:mysql:music","MYSQLUSER","MYSQLPASS") or die "Can't connect to MySQL DB : $!";
$sth = $dbh->prepare("SELECT * FROM Album WHERE BandID=$BandID");
$sth->execute();
while ($ref = $sth->fetchrow_hashref())
	{
	push (@Album, $ref->{'AlbumName'});
	push (@AlbumID, $ref->{'AlbumID'});
	}
#
# Print out list of albums available by the requested artist.
#
print $page->header('text/html');
print "<html>\n";
print "<head>\n";
print "<title>\n";
print "Available Albums by $Artist \n";
print "</title>\n";
print "<body link=\"#0066ff\" alink=\"#0066ff\" vlink=\"#0066ff\" bgcolor=\"#0066FF\" text=\"#FFFFFF\">\n";
print "<h1>Albums by $Artist</h1>\n<br>\n";
print "<h2><b>These Are the albums available by $Artist</b></h2>\n";
$Artist =~ s/ /_/g;
foreach (@Album)
	{
	print "<a href=$script?AlbumID=$AlbumID[$x]&Artist=$Artist&Album=$_ 
		onmouseover=\"document.images[$x].src='/img/button2.gif' \; return true\;\"
		onmouseout=\"document.images[$x].src='/img/button.gif' \; return true\;\"> 
		<img src='/img/button.gif'></a>"; 
	s/_/ /g;
	print "$_ <br> \n";	
	$x++;
	}
#
# Disconnect from database;
#
$sth->finish;
$dbh->disconnect;
}


sub Album 
{
my @SongName;
my @SongPath;
my @TrackNumber;
my @TrackID;
#
# Build a random port number.
# 
my $x    = 0;
my $A    = int(rand(10));
my $B    = int(rand(10));
my $C    = int(rand(10));
my $port = "8$A$B$C";
#
# Connect to the DB and grab info
#
$dbh = DBI->connect("DBI:mysql:music","MYSQLUSER","MYSQLPASS") or die "Can't connect to MySQL DB : $!";
$sth = $dbh->prepare("SELECT * FROM Song WHERE AlbumID=$AlbumID");
$sth->execute();
while ($ref = $sth->fetchrow_hashref())
	{
	push (@SongName, $ref->{'SongName'});
	push (@SongPath, $ref->{'SongPath'});
	push (@TrackNumber, $ref->{'TrackNumber'});
	push (@TrackID, $ref->{'TrackID'});
	}
#
# Pull underscores for display purposes
#
$Artist =~ s/_/ /g;
$Album  =~ s/_/ /g;
#
# Print out Track listing for requested album and
# a link at the bottom to stream that album.
#
print $page->header('text/html');
print "<html>\n";
print "<head>\n";
print "<title>\n";
print "$Album by $Artist\n";
print "</title>\n";
print "<script language=\"javascript\"></script>\n";
print "</head>\n";
print "<body link=\"#FFFFFF\"  alink=\"#FFFFFF\" vlink=\"#FFFFFF\" bgcolor=\"#0066FF\" text=\"#FFFFFF\">\n";
print "<h1>Track Listing For $Album by $Artist</h1><br>\n";
foreach (@SongName)
	{
	s/.mp3//g;
	s/_/ /g;
	print "$TrackNumber[$x] - $_ \n<br>";
	$x++;
	}
$Artist =~ s/ /_/g;
$Album  =~ s/ /_/g;
print "<h2>\n<b>\n";
print "<a href = /cgi-bin/Music.pl?Stream=1&AlbumID=$AlbumID&port=$port&Album=$Album&Artist=$Artist>Play This Album</a>\n";
print "</h2>\n</b>\n";
print "</body>\n";
print "</html>\n";
}

sub Stream
{
#
# This is a little tricky, we need to fork off a child
# process for the stream. Theres a few different reasons
# for it, just trust me on it.
#
FORK:
{
if ($pid = fork)
{
#
# The two playlists we need to create
#
$play = "DOCROOT/playlist/$port.m3u";
$list = "DOCROOT/playlist/playlist.$port";
#
# Create the playlist for the client.
#
open  PLAYLIST, ">$play" or die "couldn't open $play : $!\n";                                 
print PLAYLIST  "#EXTM3U \n";                                
print PLAYLIST  "#EXTINF:-1, Streaming Server \n";
print PLAYLIST  "http://$ServerAddr:$port \n";
close PLAYLIST;
#
# Create the playlist for the server.
#
open LIST, ">$list";
$dbh = DBI->connect("DBI:mysql:music","MYSQLUSER","MYSQLPASS") or die "Couldn't Open DB : $!" ;
$sth = $dbh->prepare("SELECT * FROM Song WHERE AlbumID = $AlbumID");
$sth->execute();
while ($ref = $sth->fetchrow_hashref())
        {
        $buffer = join '', $ref->{'SongPath'}, $ref->{'SongName'} or die "Join : $! \n";
        print LIST "$buffer \n";
        }
$sth->finish or die "Couldn't close \$sth : $! ";
$dbh->disconnect or die "Couldn't disconnect \$dbh : $! ";
close LIST;
#
# Print the redirect page to send the clients plalyist to the client.
#
print $page->header('text/html');
print "<html>\n";
print "<head>\n";
print "<title>\n";
print "Streaming to You now\n";
print "</title>\n";
print "<script language=\"javascript\"></script>\n";
print "</head>\n";
print "<body onload=\"document.location=\'http://$ServerAddr/playlist/$port.m3u\'\">\n";
print "If the stream doesn't start in within ten seconds, click <a href = /playlist/$port.m3u > here </a> to start it \n";
print "</body>\n";
print "</html>\n\n";

}
        elsif (defined $pid)
{
# 
# First thing we have to do here is close STDOUT so that the 
# Client doesn't wait on the script to send it more info.
# then we start the stream, it's painfully straightforward...
#
close STDOUT;
system "STREAMEXEC/Stream.pl $port $Artist $Album" or die "Couldn't Execute Stream : $! \n";
}
else
{
die "Couldn't fork : $! \n";
}}}

