#!/usr/bin/perl
#
# MythWeb Streaming/Download module
#
# @url       $URL: http://svn.mythtv.org/svn/branches/release-0-22-fixes/mythplugins/mythweb/modules/stream/tv.pl $
# @date      $Date: 2009-03-05 01:47:23 -0600 (Thu, 05 Mar 2009) $
# @version   $Revision: 20110 $
# @author    $Author: kormoc $
#
# This file was customized by takeone

    use Sys::Hostname;

# Attempt to use the perl bindings to prevent the backend from shutting down during streaming
    eval 'use MythTV;';

    if (!$@) {
        our $mythbackend = new MythTV();
        $mythbackend->backend_command('ANN Playback '.hostname);
    }

# Which show are we streaming?
    our $chanid    = url_param('chanid');
    our $starttime = url_param('starttime');
    if ($Path[1]) {
        $chanid    = $Path[1];
        $starttime = $Path[2];
        $starttime =~ s/\.\w+$//;
    }

# Get the basename from the database
    my $sh = $dbh->prepare('SELECT basename, title, subtitle, endtime-starttime
                              FROM recorded
                             WHERE starttime=FROM_UNIXTIME(?)
                                   AND recorded.chanid   = ?');
    $sh->execute($starttime, $chanid);
    our ($basename, $title, $subtitle, $runtime) = $sh->fetchrow_array();
    $sh->finish;

# Decode $title and $subtitle to sjis (for Japanese IE and Firefox) 
# If you use another no-ascii letters, you can use Encode::Decode module, may be
    use Jcode;
    $title = jcode($title)->sjis;
    $subtitle = jcode($subtitle)->sjis;
  
# No match?
    unless ($basename =~ /\w/) {
        print header(),
              "Unknown recording requested.\n";
        exit;
    }

# Find the local file
    our $filename;
    $sh = $dbh->prepare('SELECT DISTINCT dirname
                           FROM storagegroup');
    $sh->execute();
    while (my ($video_dir) = $sh->fetchrow_array()) {
        next unless (-e "$video_dir/$basename");
        $filename = "$video_dir/$basename";
        last;
    }
    $sh->finish;

    1;
