Monday, November 10, 2008

Updated Bash Script To Get Cable, Dish and Local TV Listings

Hey There,

For this week's Monday Linux/Unix bash shell script, we're following up on our script from last week, with more user suggested improvements, that makes it so you can get your local TV listings from the command line with bash. This week's script is an update to include a lot of error checking and (from the suggestion I received the most often :) the ability to pick a time span. This script's invocation will allow you to get listings from "right now" (or whatever you set the "time" variable to) to the regular 3 hour time span in half-hour increments. The next paragraph is a blatant homage (read: shameless self promotion) to "other scripts we've done before that follow along the lines of this one." Please skip it and move on to next paragraph unless you enjoy reading lists for the sake of list reading :)

Our previous web-based Bash scripts, in backward chronological order, include our posts on accessing Wikipedia, accessing the Farmer's Almanac, accessing the International Dictionary, checking out the world's weather, spewing out famous quotations on pretty much any subject, doing encyclopedia lookups, accessing the online Thesaurus, translating between different languages and, of course, using the online dictionary.

This script still gets its content from the TV Listings At Zap2It.com and includes a lot of error fixes. Most importantly, though, it allows you to pick your time slot (assuming you don't want the full 3 hour spread), shown in the usage message like this:

host # ./cabletv.sh -h

Usage: ./cabletv.sh ...all options are optional [-h for help]
[-z USZipCode] [-p LocalCableOrDishProviderID]
[-t Time] [-d date] [-n to leave out HD channel info]
[-s ListingTimeSpan 1 for just now, 2 for an additional half
hour, 3, 4, 5, 6, in half hour increments, and 7 for 3 hours
...defaults to 7 since this is the online listing default]


Much of the error checking was done so that the script would capture bad zip codes, invalid time specifications and make it so you can set your date in a more free manner (output below does not include actual listings to make the picture smaller):

Click on the picture below for a graphic depiction of some of the code fixes ;)

cable tv script errors

After that, check out the next few pictures below, which show successful executions and the beginning of the TV listings. The first picture shows the output from a "right now" execution and the other is from an "2 hour" execution. The default time span is 3 hours, since that's the way it is online:

Click on the pictures below and prepare for the mediocrity ;)

tv listings for right now

2 hours of tv listings

I'd like to thank everyone who wrote in with comments and suggestions (which I'll continue to post online, as possible). The script is starting to get better, but it's still far from perfect. Hopefully you find it more helpful now :)

I still need to put out those movie/favorites filters. Soon... Soon... ;)

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/bin/bash

#
# cabletv.sh - Get your local regular and HD Tv listings
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#
# UPDATE FOR 11/9/2008
# TODO You have entered an invalid ZIP or postal code
# TODO am to pm or pm to am ends up not in chronological order
# TODO 12 to 1 a/p ends up not in chronological order
# TODO switch to enhanced getopt to deal with variable argument switches
# TODO add config file
# TODO check for bad provider code
# DONE check for bad zip code
# DONE added optional time increments - up to 3 hours - for display
# DONE tightened up code using indirect variable references
# DONE date may now be entered in quotes numeric or alpha - e.g. 11/9/08 11/09/2008 "Nov 9 2008" "November 9th 2008" etc
# DONE time may now be entered as 10pm 10 (with am/pm defaulting to system time) 10:00am 23:00 etc
# DONE added error checking for invalid date and time entry - stop before querying online guide
# DONE fixed issue with 00:xx time causing script failure
# DONE added extra error checking
#

function usage()
{
echo
echo "Usage: $0 ...all options are optional [-h for help]"
echo "[-z USZipCode] [-p LocalCableOrDishProviderID]"
echo "[-t Time] [-d date] [-n to leave out HD channel info]"
echo "[-s ListingTimeSpan 1 for just now, 2 for an additional half"
echo "hour, 3, 4, 5, 6, in half hour increments, and 7 for 3 hours"
echo "...defaults to 7 since this is the online listing default]"
echo
exit 1
}

while getopts t:z:hs:nd:p: option
do
case $option in
t)
opt_time="$OPTARG"
;;
d)
opt_date="$OPTARG"
;;
z)
opt_zip="$OPTARG"
;;
n)
opt_nohd=1
;;
p)
opt_provider="$OPTARG"
;;
s)
opt_timespan="$OPTARG"
;;
h)
usage
;;
*)
usage
;;
esac
done

wget=/usr/bin/wget
pager=/usr/bin/more

if [ ! "$opt_date" ]
then
nicedate=`date "+%m/%d/%y"`
else
nicedate=$opt_date
fi

if [ ! $opt_timespan ]
then
opt_timespan=7
elif [ $opt_timespan -lt 1 -o $opt_timespan -gt 7 ]
then
usage
fi

if [ ! $opt_time ]
then
hour=`date "+%I"`
minute=`date "+%M"`
ampm=`date "+%p"`
if [ $hour -lt 12 ]
then
if [ $minute -lt 30 ]
then
nicetime="${hour}:00 AM"
else
nicetime="${hour}:30 AM"
fi
else
if [ $minute -lt 30 ]
then
nicetime="${hour}:00 PM"
else
nicetime="${hour}:30 PM"
fi
fi
if [ $hour == "00" ]
then
cli_time=${hour}:${minute}
else
cli_time=${hour}:${minute}${ampm}
fi
else
cli_time=$opt_time
fi

date_ok=`date -d "$cli_time" +%s 2>&1`
if [[ "$date_ok" =~ "invalid date" ]]
then
echo
echo "INVALID TIME ENTERED: $opt_time"
echo "Be sure to include full am or pm"
echo "and do not add am or pm to 24 clock entries"
echo
usage
fi

ampm=`echo $opt_time|egrep 'a|p|m' 2>&1`
result2=$?
if [ $result2 -eq 0 ]
then
date_ok2=`echo $opt_time|egrep 'a|p'|grep m 2>&1`
result3=$?
if [[ $result3 -ne 0 ]]
then
echo
echo "INVALID TIME ENTERED: $opt_time"
echo "Be sure to include full am or pm"
echo "and do not add am or pm to 24 clock entries"
echo
usage
fi
fi

cli_time2=`date -d "$cli_time" +%s`
let fromtime1=$cli_time2*1000
let fromtime2=$fromtime1+1800000
let fromtime3=$fromtime2+1800000
let fromtime4=$fromtime3+1800000
let fromtime5=$fromtime4+1800000
let fromtime6=$fromtime5+1800000
let fromtime7=$fromtime6+1800000
if [ ! $opt_timespan ]
then
opt_timespan=7
fi

timespan_relay="$fromtime1"
timespan_counter=2
timespan_limit=$opt_timespan

while [ $timespan_limit -gt 1 ]
do
nextup_time=$(eval "echo \$$(echo fromtime${timespan_counter})")
timespan_relay="$timespan_relay $nextup_time"
let timespan_counter=$timespan_counter+1
let timespan_limit=$timespan_limit-1
done

from_timespan=$(eval "echo \$$(echo fromtime${opt_timespan})")
cli_time_end=`echo $from_timespan|awk '{printf("%20s",strftime("%I:%M %p - %x", $0 / 1000))}'`

if [ ! $opt_nohd ]
then
opt_nohd=0
fi

if [ ! $opt_zip ]
then
echo -n "Enter Zip Code: "
read zip_code
else
zip_code=$opt_zip
fi

$wget -nv -O - "http://tvlistings.zap2it.com/tvlistings/ZBChooseProvider.do?method=getProviders&zipcode=${zip_code}" 2>&1|sed -e :a -e 's/<[^>]*>/ /g;/</N;//ba' |sed -e '/^[ \t]*$/d' 2>&1|grep "You have entered an invalid ZIP or postal code" >/dev/null 2>&1
zip_ok=$?

if [ $zip_ok -eq 0 ]
then
echo
echo "INVALID ZIP CODE ENTERED: $opt_zip"
echo
usage
fi

if [ ! $opt_provider ]
then
$wget -nv -O - "http://tvlistings.zap2it.com/tvlistings/ZBChooseProvider.do?method=getProviders&zipcode=${zip_code}" 2>&1|sed 's/<.*&lineupId=\([^&]*\)\">/\1 \c/'|sed -e :a -e 's/<[^>]*>/ /g;/</N;//ba' |sed -e '/^[ \t]*$/d' |sed -e '1,/Choose Your Provider/{x;$!d;x;q;};x;$G' -e '/document.write/,$d' -e "s/'/'/" -e 's/&/\&/' -e 's/^[ \t]*//;s/[ \t]*$//'|sed '/\([A-Za-z0-9_][A-Za-z0-9_]*:[-X]\)/ {
N
s/ *\n/ \t/g
}'
echo "Enter Provider ID [e.g. \"IL57303:-\" \"4DTV:-\" \"IL12561:X]\""
read tv_provider
else
tv_provider=$opt_provider
fi

echo
echo "Television Listings for $nicedate from $cli_time to $cli_time_end"
echo

last=1

if [ $opt_nohd -eq 1 ]
then
for x in $timespan_relay
do
$wget -nv -O - "http://tvlistings.zap2it.com/tvlistings/ZCGrid.do?fromTimeInMillis=${x}&method=decideFwdForLineup&zipcode=${zip_code}&setMyPreference=false&lineupId=${tv_provider}" 2>&1|sed 's/<.*&sch=\([^&]*\)&[^>]*>/\1 /'|sed -e :a -e 's/<[^>]*>/ /g;/</N;//ba' |sed -e '/^[ \t]*$/d' |sed -e '1,/Forgotten password/d' -e '/isFavoritesAvailable/,$d'|sed -e '/[ECMP][SD]T/,+6d' -e "s/'/'/" -e 's/&/\&/' -e '/zc.getAdFrame/d' -e 's/^[ \t]*//;s/[ \t]*$//'| sed -n '/^[0-9][0-9]*$/,+2p'|sed 's/^\([0-9][0-9]*\)$/\n\1/'|sed '/^[0-9][0-9]*$/ {
N
N
s/ *\n/\t/g
}'|awk '{ if ( $1 ~ /^[0-9]/ ) {printf("%-4s %-8s ", $1,$2);for (i=4;i<NF+1;i++) {printf("%s ", $i)};printf("%20s %-20s", "*** Start",strftime("%x - %I:%M %p",$3 / 1000));print ""}}'
done|sort -t'-' -k1,1n -k2,3n | uniq|while read one two three;do if [ $one -eq $last ];then echo " $three";last=$one;else echo "$one $two $three";last=$one;fi;done|$pager
else
for x in $timespan_relay
do
$wget -nv -O - "http://tvlistings.zap2it.com/tvlistings/ZCGrid.do?fromTimeInMillis=${x}&method=decideFwdForLineup&zipcode=${zip_code}&setMyPreference=false&lineupId=${tv_provider}" 2>&1|sed 's/<.*&sch=\([^&]*\)&[^>]*>/\1 /'|sed -e :a -e 's/<[^>]*>/ /g;/</N;//ba' |sed -e '/^[ \t]*$/d' |sed -e '1,/Forgotten password/d' -e '/isFavoritesAvailable/,$d'|sed -e '/[ECMP][SD]T/,+6d' -e "s/'/'/" -e 's/&/\&/' -e '/zc.getAdFrame/d' -e 's/^[ \t]*//;s/[ \t]*$//'| sed -n '/^[0-9][0-9]*\.*[0-9]*$/,+2p'|sed -e 's/^\([0-9][0-9]*\.*[0-9]*\)$/\n\1/'|sed '/^[0-9][0-9]*\.*[0-9]*$/ {
N
N
s/ *\n/\t/g
}'|awk '{ if ( $1 ~ /^[0-9]/ ) {printf("%-4s %-8s ", $1,$2);for (i=4;i<NF+1;i++) {printf("%s ", $i)};printf("%20s %-20s", "*** Start",strftime("%x - %I:%M %p",$3 / 1000));print ""}}'
done|sort -t'-' -k1,1n -k2,3n | uniq|while read one two three;do if [ "$one" == "$last" ];then echo " $three";last=$one;else echo "$one $two $three";last=$one;fi;done|$pager
fi

exit 0


, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.