#!/usr/local/bin/perl -w

# scrape listener count from stream server page
# timestamp and send as CSV to stdout for import into m$oft excel.

use strict;
use LWP 5.64;

# should also work for other SHOUTcast D.N.A.S. servers
use constant URL	=> "http://sc1.mainstreamnetwork.com:9042/";

use constant INTERVAL	=> 15 * 60;
use constant OFFSET	=> 22 * 60 + 30; # = 450 mod (15 * 60), or 7.5 minutes
use constant FF_HEADERS => (
   'User-Agent' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1',
   'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
   'Accept-Language' => 'en-us,en;q=0.5',
   'Accept-Encoding' => 'gzip,deflate',
   'Accept-Charset:' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
); # at minimum User-Agent is required to fetch page instead of stream

# autoflush on
$|++;

my $browser = LWP::UserAgent->new;
my $page;
my $nlisteners;
my $comment;
my @weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
my ($second, $minute, $hour, $dayOfMonth, $month, $year, $dayOfWeek, $dayOfYear, $daylightSavings);

while (1)
{
   $page = $browser->get(URL, FF_HEADERS);
   if ($page->is_success) {
      $nlisteners = $page->content;
      $nlisteners =~ s/.*with <B>(\d+)(.*)/$1/;
      if ($nlisteners !~ /\d+/ ) {
      	$nlisteners = 0;
	$comment = 'Failed to extract listener count from: ' . $page->content;
      } else {
      	$comment = '';
      }
   } else {
      $comment = 'GET failed: ' . $page->status_line;
   }
   ($second, $minute, $hour, $dayOfMonth, $month, $year,
    $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
   $month++; # localtime() uses 0 for january, but excel uses 1
   $year += 1900;
   printf "\"%4d-%02d-%02d %02d:%02d:%02d\",\"%d\",\"%s\",\"%s\"\n",
	  $year, $month, $dayOfMonth, $hour, $minute, $second,
	  $nlisteners, $weekDays[$dayOfWeek], $comment;
   # sleep until the middle of the next quarter hour
   sleep(OFFSET - (($minute * 60 + $second) % INTERVAL));
}
