Skip to content

Instantly share code, notes, and snippets.

@sankalp-khare
Created August 23, 2012 20:07
Show Gist options
  • Save sankalp-khare/3440990 to your computer and use it in GitHub Desktop.
Save sankalp-khare/3440990 to your computer and use it in GitHub Desktop.
tvrage script
#!/usr/bin/python
# Author: Sankalp Khare
# Email: sankalpkhare@gmail.com
import sys
import urllib2
import re
import datetime
from optparse import OptionParser
def checkEpSyntax(ep):
epRegEx = re.compile('\d+x\d+')
matchObject = epRegEx.match(ep)
if matchObject:
if matchObject.span() == (0,len(ep)):
return True
else:
return False
else:
return False
def getTVrageURL(show,episode,exact):
URL = "http://services.tvrage.com/tools/quickinfo.php?"
show = show.replace(" ","%20")
URL+=("show="+show)
if episode:
URL+=("&ep="+episode)
else:
URL+=('&ep=""')
if exact:
URL+=("&exact=1")
else:
URL+=("&exact=0")
return URL
def makeDict(info):
info = info.splitlines()
dict = {}
for line in info:
line = line.split('@')
dict[line[0]] = line[1]
return dict
def dtObj(ts):
splitRegEx = re.compile('(\d+-\d+-\d+T\d+:\d+:\d+)(.*)')
matchObject = splitRegEx.match(ts)
UTCtimestr = matchObject.group(1)
d = datetime.datetime.strptime(UTCtimestr,"%Y-%m-%dT%H:%M:%S")
offset = matchObject.group(2)
offsetSplitRegEx = re.compile('([+-])(\d+):(\d+)')
offsetMatchObject = offsetSplitRegEx.match(offset)
offsetHours = int(offsetMatchObject.group(2))
offsetMinutes = int(offsetMatchObject.group(3))
if offsetMatchObject.group(1) == "-":
offsetHours*=-1
offsetMinutes*=-1
td = datetime.timedelta(hours=offsetHours,minutes=offsetMinutes)
UTCAirTime = d - td
return UTCAirTime
def stripMilliSeconds(deltastr):
stripRegEx = re.compile('(.*)\..*')
matchObject = stripRegEx.match(deltastr)
return matchObject.group(1)
def printInfo(dict):
print
if dict.has_key("Episode Info"):
width = len(dict["Show Name"])+len(dict["Episode Info"])+13
epInfo = dict["Episode Info"].split('^')
print '+'+'-'*width+'+'
print "| "+dict["Show Name"]+" "+epInfo[0]+" "+epInfo[1]+", Aired on "+epInfo[2]+" |"
print '+'+'-'*width+'+'
print
print "</pre><a target=\"_blank\" href=\"",
print dict["Episode URL"]
print "\">%s, %s %s @ TVRage.com</a><pre>" %(dict["Show Name"],epInfo[0],epInfo[1])
print
print "+ Country : %s" % (dict["Country"])
print "+ Network : %s" % (dict["Network"])
if dict.has_key("Airtime"):
print "+ Airing time : %s" % (dict["Airtime"])
print "+ Runtime (min) : %s" % (dict["Runtime"])
else:
width = len(dict["Show Name"])+len(dict["Premiered"])+17
print '+'+'-'*width+'+'
print "| "+dict["Show Name"]+", Premiered in "+dict["Premiered"]+" |"
print '+'+'-'*width+'+'
print
print "</pre><a target=\"_blank\" href=\"",
print dict["Show URL"]
print "\">%s @ TVRage.com</a><pre>" %(dict["Show Name"])
print
print "+ Started on : %s" % (dict["Started"])
print "+ Status : %s" % (dict["Status"])
if dict["Ended"]:
print "+ Ended on : %s" % (dict["Ended"])
print "+ Country : %s" % (dict["Country"])
print "+ Network : %s" % (dict["Network"])
if dict.has_key("Airtime"):
print "+ Airing time : %s" % (dict["Airtime"])
print "+ Classification : %s" % (dict["Classification"])
print "+ Genre(s) : %s" % (dict["Genres"])
print "+ Runtime (min) : %s" % (dict["Runtime"])
if dict.has_key("Latest Episode"):
latestEpInfo = dict["Latest Episode"].split('^')
print "+ Latest episode : %s %s, Aired on %s" % (latestEpInfo[0],latestEpInfo[1],latestEpInfo[2])
if dict.has_key("Next Episode"):
nextEpInfo = dict["Next Episode"].split('^')
print "+ Upcoming Episode : %s %s, Airing on %s" % (nextEpInfo[0],nextEpInfo[1],nextEpInfo[2])
try:
utcairtime = dtObj(d["RFC3339"])
runtimeDelta = datetime.timedelta(minutes=int(dict["Runtime"]))
utcendtime = utcairtime + runtimeDelta
timenow = datetime.datetime.utcnow()
print "</pre><font color=\"green\"><pre>"
if timenow > utcairtime:
tta = timenow - utcairtime
print "+ Next Ep Aired :",
print stripMilliSeconds(str(tta)),
print "ago"
else:
tta = utcairtime - timenow
print "+ Next Ep Airs in :",
print stripMilliSeconds(str(tta))
print "</pre></font><font color=\"red\"><pre>"
if timenow > utcendtime:
tte = timenow - utcendtime
print "+ Next Ep Ended :",
print stripMilliSeconds(str(tte)),
print "ago"
else:
tte = utcendtime - timenow
print "+ Next Ep Ends in :",
print stripMilliSeconds(str(tte))
print "</pre></font><pre>"
except KeyError:
print "</pre><pre>"
print "+ Next Ep Airs in : Info Unavailable"
print
# Script description
desc = "Get information about a TV Show (or a particular episode) right from your command line!"
# Initialize Option Parser
parser = OptionParser(description=desc)
# Add options
parser.add_option("-s","--show",
dest="show",
help="Show Name, quoted in case of multiple words",
metavar="SHOW")
parser.add_option("-e","--episode",
dest="episode",
help="Episode, specified as 2x4, 7x12 etc.",
metavar="EPISODE")
parser.add_option("-E","--exact",
dest="exact",
default=False,
action='store_true',
help="search for the Exact show name specified")
# Parse arguments
(options,args) = parser.parse_args()
# Check for some mandatory Options
if options.show is None:
parser.print_help()
sys.exit(1)
elif options.episode and checkEpSyntax(options.episode) == False:
parser.print_help()
sys.exit(1)
# URL in which the values will be substituted
URL = getTVrageURL(options.show,options.episode,options.exact)
proxy_info = {
# 'user' : 'username',
# 'pass' : 'password',
'host' : "facultyproxy.iiit.ac.in",
'port' : 8080 # or 8080 or whatever
}
# build a new opener that uses a proxy requiring authorization
proxy_support = urllib2.ProxyHandler({"http" : \
"http://%(host)s:%(port)d" % proxy_info})
#"http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info})
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
# install it
urllib2.install_opener(opener)
f = urllib2.urlopen(URL)
info = f.read()
info = info.split("<pre>")
try:
d = makeDict(info[1])
except:
print "%s : Unable to find show by this name\nPerhaps being more precise will help...\n" % (options.show)
sys.exit(0)
printInfo(d)
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment