#!/usr/bin/perl


# createXSPFplaylist.pl# creates# a# XSPF# playlist# from# your# VDR# system.
# Information# is# gatheres# via# SVDRP# from# a# running# VDR# system.
# Copyright# (C)# 2007# Tuxevara# <tuxevara@googlemail.com>
# 
# This# program# is# free# software;# you# can# redistribute# it# and/or
# modify# it# under# the# terms# of# the# GNU# General# Public# License
# as# published# by# the# Free# Software# Foundation;# either# version# 2
# of# the# License,# or# (at# your# option)# any# later# version.
# 
# This# program# is# distributed# in# the# hope# that# it# will# be# useful,
# but# WITHOUT# ANY# WARRANTY;# without# even# the# implied# warranty# of
# MERCHANTABILITY# or# FITNESS# FOR# A# PARTICULAR# PURPOSE.# See# the
# GNU# General# Public# License# for# more# details.
# 
# You# should# have# received# a# copy# of# the# GNU# General# Public# License
# along# with# this# program;# if# not,# write# to# the# Free# Software
# Foundation,# Inc.,# 51# Franklin# Street,# Fifth# Floor,# Boston,# MA# 02110-1301,# USA.
# 
# Most# part# of# the# code# was# taken# from# svdrpsend.pl# which# is# part# of# the# video
# disk# recorder# VDR,# which# is# also# released# under# the# terms# of# the# GPL.
 
$ENCODING="ISO-8859-1";


### DO NOT MAKE ANY CHANGES BEYOND THIS LINE ###

use Getopt::Std;
use Socket;

$Usage = qq{
Usage: $0 options command...

Options: -d hostname        destination hostname (default: localhost)
         -p port            SVDRP port number (default: 2001)
};

die $Usage if (!$ARGV[0] || !getopts("d:p:"));

$Dest = $opt_d || "localhost";
$Port = $opt_p || 2001;

$Timeout = 10; # max. seconds to wait for response

$SIG{ALRM} = sub { Error("timeout"); };
alarm($Timeout);

$iaddr = inet_aton($Dest)                   || Error("no host: $Dest");
$paddr = sockaddr_in($Port, $iaddr);

$proto = getprotobyname('tcp');
socket(SOCK, PF_INET, SOCK_STREAM, $proto)  || Error("socket: $!");
connect(SOCK, $paddr)                       || Error("connect: $!");
select(SOCK); $| = 1;

Send("LSTC");
Send("QUIT");
close(SOCK)                                 || Error("close: $!");

print STDOUT "<?xml version=\"1.0\" encoding=\"$ENCODING\"?><playlist version=\"0\" xmlns=\"http://xspf.org/ns/0/\"><title>VDR</title><trackList>$tracklist</trackList></playlist>";

sub Send
{
    my $cmd = shift || Error("no command to send");
    print SOCK "$cmd\r\n";
    Receive();
}

sub Receive
{

    while (<SOCK>) {
        if ($_ =~ /^250[-\s](\w+) ([^:;,]+).*/) {
            $ch_nr = $1;
            $ch_name = $2;
            $ch_name =~ s/\&/ and /g ;
            $tracklist .= "<track><location>http://$Dest:3000/PES/$ch_nr</location><title>$ch_name</title></track>\n";
        }
        last if substr($_, 3, 1) ne "-";
    }
}

sub Error
{
    print STDERR "@_\n";
    close(SOCK);
    exit 0;
}

