import urllib2, os, time

def get_ldata(url, headers = None):    
    if headers is None:
        headers = {'User-agent': 'XBMC/13.2 Git:20140817-0f3db05 (Windows NT 6.1;WOW64;Win64;x64; http://xbmc.org)'}
    req = urllib2.Request(url, None, headers)
    response = urllib2.urlopen(req)
    data = response.read()
    response.close()
    return data

def makefileW(fpath, data):    
    text_file = open(fpath, "w")
    text_file.write(data)
    text_file.close()
  
def readfile(fpath):
    data = ''
    text_file = open(fpath, "r")
    data = text_file.read()
    text_file.close()
    return data
#try:
import sys
tkndata = sys.argv[1].split('^') # first parameter
if os.path.exists(tkndata[1]+'/sessions/'+tkndata[0]+".ses") == False:    
    if(get_ldata('http://www.liveexpress.net/secured/php/chnlmgr/auth.php?chnl='+tkndata[1]+'&uid='+tkndata[0].split('-')[1]+'&token='+tkndata[0].split('-')[0]+'&ip='+tkndata[2])=="Success"):
        makefileW(tkndata[1]+'/sessions/'+tkndata[0]+".ses", str(time.time()).split('.')[0]+"^"+tkndata[2]+"^"+str(time.time()).split('.')[0]+"^"+tkndata[3])
        import mysql.connector
        cnx = mysql.connector.connect(user='sam', password='jigna1234',host='127.0.0.1', database='sam')
        cursor = cnx.cursor()
        query = "REPLACE INTO `strusers`(`uid`, `ip`, `token`, `chnl`, `tkntime`, `uagent`) VALUES (%s, %s, %s, %s, %s, %s)"
        cursor.execute(query, (tkndata[0].split('-')[1], tkndata[2], tkndata[0].split('-')[0], tkndata[1], str(time.time()), tkndata[3]))
        cnx.commit()
        cnx.close()
        print "GO"
    else:
        print "STOP"
else:
    oldtkndata = readfile(tkndata[1]+'/sessions/'+tkndata[0]+".ses").split('^')
    if(oldtkndata[1]==tkndata[2]):
        if(time.time()-int(oldtkndata[2])>90):
            import mysql.connector
            cnx = mysql.connector.connect(user='sam', password='jigna1234',host='127.0.0.1', database='sam')
            cursor = cnx.cursor()
            query = "SELECT * FROM `strusers` WHERE `uid`=%s AND `token`=%s AND `chnl`=%s"
            cursor.execute(query, (tkndata[0].split('-')[1], tkndata[0].split('-')[0], tkndata[1]))
            msg = cursor.fetchone()
            cnx.close()
            if(msg):
                makefileW(tkndata[1]+'/sessions/'+tkndata[0]+".ses", oldtkndata[0]+"^"+tkndata[2]+"^"+str(time.time()).split('.')[0]+"^"+tkndata[3])
                print "GO"
            else:
                print "STOP"
        else:    
            makefileW(tkndata[1]+'/sessions/'+tkndata[0]+".ses", oldtkndata[0]+"^"+oldtkndata[1]+"^"+oldtkndata[2]+"^"+tkndata[3])
            print "GO"
    else:
        print "STOP"
#except:
    #print "STOP"
