# -*- coding: utf-8 -*-
'''
Copyright 2010 Tomáš Heřman

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''

'''
TODO:		-error handling
'''
import urllib2
import cookielib
import urllib
import StringIO
import re
import os
from optparse import OptionParser
from string import Template

class GomHaxxerException(Exception):
	reportData = None
	feedback = False;
	def __init__(self,message,feedback=False,reportData={}):
		self.message = message
		self.reportData = reportData
		self.feedback = feedback

def which(program):
    import os
    def is_exe(fpath):
        return os.path.exists(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None	    

def handleFatalException(exc):
	print exc.message
	exc_type, exc_obj, exc_tb = os.sys.exc_info()
#	print str(exc_tb.extract_stack())
	os.sys.exit(1)

def performDefaultUnixCheck():
	if which("vlc") == None:
		raise GomHaxxerException("VLC does not seems to be present in your system path. Please install VLC player for default usage.")
def performDefaultOSXCheck():
	if os.path.exists("/Applications/VLC.app") == False:
		raise GomHaxxerException("VLC does not seems to be installed in your /Application folder. Please install VLC player for default usage.")

# set up variables and constants
def main():
	try:
		defaultOSXcommandVLC = '/Applications/VLC.app/Contents/MacOS/VLC "--http-caching=$cache" "$url"'
		defaultLinuxVLC = 'vlc "--http-caching=$cache" "$url"'

		parser = OptionParser()
		parser.add_option("-p","--password",dest="password", help="Password to your GomTV account.")
		parser.add_option("-e","--email",dest="email", help="Email your GomTV account uses.")
		parser.add_option("-b",action="store_true",dest="hq", help="Use better quality stream. (Default)")
		parser.add_option("-l",action="store_false",dest="hq", help="Use lower quality stream")
		parser.add_option("-c","--command",dest="command", help="Customg command to run.")
		parser.add_option("-d","--buffer-time",dest="cache",help ="Cache size in [ms]")

		parser.set_defaults(hq=True)
		if os.uname()[0] == 'Darwin':
			parser.set_defaults(command=defaultOSXcommandVLC)
		else:
			parser.set_defaults(command=defaultLinuxVLC)
		parser.set_defaults(cache=30000)
		(options,args) = parser.parse_args()
		if options.command == defaultLinuxVLC:
			performDefaultUnixCheck()
		elif options.command == defaultOSXcommandVLC:
			performDefaultOSXCheck()
		url = getStreamURL(options.email,options.password)

		command = Template(options.command)
		commandArgs = {
						'cache':options.cache,
						'url':url
					   }
		cmd = command.substitute(commandArgs)
		print(cmd)
		os.system(cmd)
	except GomHaxxerException as ex:
		handleFatalException(ex)

def getStreamURL(email,password,hq=True):
	gomtvURL = "http://www.gomtv.net"
	gomtvLiveURL= gomtvURL + "/2010gslopens3/live/"
	gomtvSignInURL= gomtvURL + "/user/loginProcess.gom"
	values = {'cmd' : 'login',
			  'returl' : '%2F',
			  'mb_username' : email,
			   'mb_password': password,
			  }
	data = urllib.urlencode(values)
	cookiejar = cookielib.LWPCookieJar()

	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))

	request = urllib2.Request(gomtvSignInURL,data)
	urllib2.install_opener(opener)
	urllib2.urlopen(request)
	if(len(cookiejar)==0):
		raise GomHaxxerException("Authentification failed! Please check your login and password!")

	request = urllib2.Request(gomtvLiveURL)
	response= urllib2.urlopen(request)
	urls = parseURLs(response.read())
	print urls
	if len(urls)==0:
		raise GomHaxxerException("No URL's found! Are you sure the stream is live?")
	if(hq == True):
		url = parseHQStreamURL(urls)
	else:
		url = parseLQStreamURL(urls)
	request = urllib2.Request(url)
	response = urllib2.urlopen(request)
	return parseStreamURL(response.read())



def parseURLs(response):
	patternGOMCMD = r"gomcmd://[^;]+;"
	commands = re.findall(patternGOMCMD,response)
	return map(parseHTTPofCmd,commands)
def parseHTTPofCmd(item):
	patternHTTP = r"(http://[^;]+)';"
	if re.search(patternHTTP,item) != None:
		return re.search(patternHTTP,item).group(1)
	else:
		raise GomHaxxerException("Something weird is going on! gomcmd:// commands were found while no http:// command was found! item: [" + item + "]")
def parseHQStreamURL(urls):
	hqStreamPattern = r".*HQ.*"
	return parseStreamFileURL(urls,hqStreamPattern)
def parseLQStreamURL(urls):
	lqStreamPattern = r".*SQ.*"
	return parseStreamFileURL(urls,lqStreamPattern)
def parseStreamFileURL(urls,pattern):
	for url in urls:
		if re.match(pattern,url):
			return url
def parseStreamURL(response):
	streamPattern = r'<REF href= "([^"]*)"/>'
	return re.search(streamPattern,response).group(1)



if __name__=="__main__":
	main()

