import urllib,urllib2,re,xbmcplugin,xbmcgui,os,sys,datetime,string,hashlib,net
import plugintools
import xbmcaddon
import liveresolver
import xbmcaddon
from cookielib import CookieJar

net = net.Net()

ADDON = xbmcaddon.Addon(id='plugin.video.freeview')
DATA_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.freeview'), '')
addon_id = xbmcaddon.Addon().getAddonInfo('id')
selfAddon = xbmcaddon.Addon(id=addon_id)
icon = xbmc.translatePath(os.path.join('special://home/addons/plugin.video.freeview', 'icon.jpg'))
fanart = xbmc.translatePath(os.path.join('special://home/addons/plugin.video.freeview', 'fanart.jpg'))
logos = xbmc.translatePath(os.path.join('special://home/addons/plugin.video.freeview/resources/logos', ''))
logos_tvp = 'https://assets.tvplayer.com/common/logos/256/Inverted/'

def CATEGORIES():
	addLink('4Music','128',2,logos_tvp+'128.png')
	addLink('5*','https://www.filmon.com/tv/5-star',1,logos+'5star.png')
	addLink('5USA','https://www.filmon.com/tv/5usa',1,logos+'5usa.png')
	addLink('Al Jazeera','146',2,logos_tvp+'146.png')
	addLink('BBC Alba','236',2,logos_tvp+'236.png')
	addLink('BBC Four','110',2,logos_tvp+'110.png')
	addLink('BBC News','111',2,logos_tvp+'111.png')
	addLink('BBC One Northern Ireland','http://vs-hls-uk-live.edgesuite.net/pool_4/live/bbc_one_northern_ireland_hd/bbc_one_northern_ireland_hd.isml/bbc_one_northern_ireland_hd-pa4%3d128000-video%3d5070000.m3u8',1,logos_tvp+'89.png')
	addLink('BBC One Scotland','http://vs-hls-uk-live.edgesuite.net/pool_5/live/bbc_one_scotland_hd/bbc_one_scotland_hd.isml/bbc_one_scotland_hd-pa4%3d128000-video%3d5070000.m3u8',1,logos_tvp+'89.png')
	addLink('BBC One Wales','http://vs-hls-uk-live.edgesuite.net/pool_3/live/bbc_one_wales_hd/bbc_one_wales_hd.isml/bbc_one_wales_hd-pa4%3d128000-video%3d5070000.m3u8',1,logos_tvp+'89.png')
	addLink('BBC One','89',2,logos_tvp+'89.png')
	addLink('BBC Parliament','345',2,logos_tvp+'345.png')
	addLink('BBC Two','90',2,logos_tvp+'90.png')
	addLink('Bloomberg','514',2,logos_tvp+'514.png')
	addLink('Box Hits','130',2,logos_tvp+'130.png')
	addLink('Box Upfront','158',2,logos_tvp+'158.png')
	addLink('CBBC','113',2,logos_tvp+'113.png')
	addLink('CBS Action','https://www.filmon.com/tv/cbs-action',1,logos+'cbsaction.png')
	addLink('CBS Drama','https://www.filmon.com/tv/cbs-drama',1,logos+'cbsdrama.png')
	addLink('CBS Reality','https://www.filmon.com/tv/cbs-reality',1,logos+'cbsreality.png')
	addLink('CBS Reality+1','https://www.filmon.com/tv/cbs-reality1',1,logos+'cbsreality.png')
	addLink('CBeebies','114',2,logos_tvp+'114.png')
	addLink('CITV','http://citvliveios-i.akamaihd.net/hls/live/207267/itvlive/CITVMN/master_Main1800.m3u8',1,logos+'citv.png')
	addLink('CNN International','286',2,logos_tvp+'286.png')
	addLink('Capital TV','157',2,logos_tvp+'157.png')
	addLink('Channel 4','92',2,logos_tvp+'92.png')
	addLink('Channel 5','93',2,logos_tvp+'93.png')
	addLink('Channel AKA','227',2,logos_tvp+'227.png')
	addLink('Chilled','226',2,logos_tvp+'226.png')
	addLink('Clubbing TV','https://www.filmon.com/tv/clubbing-tv',1,logos+'clubbingtv.png')
	addLink('Clubland','225',2,logos_tvp+'225.png')
	addLink('Community Channel','259',2,logos_tvp+'259.png')
	addLink('Dave ja vu','317',2,logos_tvp+'317.png')
	addLink('Dave','300',2,logos_tvp+'330.png')
	addLink('Drama','346',2,logos_tvp+'346.png')
	addLink('E4','https://www.filmon.com/tv/e4',1,logos+'e4.png')
	addLink('Film4','https://www.filmon.com/tv/film-4',1,logos+'film4.png')
	addLink('Food Network','125',2,logos_tvp+'125.png')
	addLink('Food Network+1','254',2,logos_tvp+'254.png')
	addLink('Forces TV','555',2,logos_tvp+'555.png')
	addLink('Heart TV','153',2,logos_tvp+'153.png')
	addLink('Home','512',2,logos_tvp+'512.png')
	addLink('Horror Channel','https://www.filmon.com/tv/horror-channel',1,logos+'horrorchannel.png')
	addLink('ITV1','204',2,logos_tvp+'204.png')
	addLink('ITV1+1','https://www.filmon.com/tv/itv-plus-1',1,logos_tvp+'204.png')
	addLink('ITV2','http://itv2liveios-i.akamaihd.net/hls/live/203495/itvlive/ITV2MN/master_Main1800.m3u8',1,logos+'itv2.png')
	addLink('ITV2+1','https://www.filmon.com/tv/itv2-plus-1',1,logos+'itv2.png')
	addLink('ITV3','http://itv3liveios-i.akamaihd.net/hls/live/207262/itvlive/ITV3MN/master_Main1800.m3u8',1,logos+'itv3.png')
	addLink('ITV3+1','https://www.filmon.com/tv/itv3-plus-1',1,logos+'itv3.png')
	addLink('ITV4','http://itv4liveios-i.akamaihd.net/hls/live/207266/itvlive/ITV4MN/master_Main1800.m3u8',1,logos+'itv4.png')
	addLink('ITV4+1','https://www.filmon.com/tv/itv4-plus-1',1,logos+'itv4.png')
	addLink('ITVBe','http://itvbeliveios-i.akamaihd.net/hls/live/219078/itvlive/ITVBE/master_Main1800.m3u8',1,logos+'itvbe.png')
	addLink('Keep It Country','569',2,logos_tvp+'569.png')
	addLink('Kerrang!','133',2,logos_tvp+'133.png')
	addLink('Kiss','131',2,logos_tvp+'131.png')
	addLink('Kix!','https://www.filmon.com/tv/kix',1,logos+'kix.png')
	addLink('London Live','http://bcoveliveios-i.akamaihd.net/hls/live/217434/3083279840001/master_900.m3u8',1,logos+'londonlive.png')
	addLink('Magic','132',2,logos_tvp+'132.png')
	addLink('More4','https://www.filmon.com/tv/more4',1,logos+'more4.png')
	addLink('NOW Music','228',2,logos_tvp+'228.png')
	addLink('POP','https://www.filmon.com/tv/pop',1,logos+'pop.png')
	addLink('Pick','https://www.filmon.com/tv/pick-tv',1,logos+'pick.png')
	addLink('QUEST','327',2,logos_tvp+'327.png')
	addLink('QUEST+1','336',2,logos_tvp+'336.png')
	addLink('QVC Beauty','250',2,logos_tvp+'250.png')
	addLink('QVC Extra','248',2,logos_tvp+'248.png')
	addLink('QVC Plus','344',2,logos_tvp+'344.png')
	addLink('QVC Style','249',2,logos_tvp+'249.png')
	addLink('QVC','247',2,logos_tvp+'247.png')
	addLink('Really','306',2,logos_tvp+'306.png')
	addLink('S4C','251',2,logos_tvp+'251.png')
	addLink('Sky News','https://www.youtube.com/watch?v=y60wDzZt8yg',1,logos+'skynews.png')
	addLink('The Box','129',2,logos_tvp+'129.png')
	addLink('The Craft Channel','554',2,logos_tvp+'554.png')
	addLink('The Jewellry Channel','545',2,logos_tvp+'545.png')
	addLink('Tiny Pop','https://www.filmon.com/tv/tiny-pop',1,logos+'tinypop.png')
	addLink('Travel Channel','126',2,logos_tvp+'126.png')
	addLink('Travel Channel+1','255',2,logos_tvp+'255.png')
	addLink('Yesterday','308',2,logos_tvp+'308.png')
	addLink('Yesterday+1','318',2,logos_tvp+'318.png')
	addLink('truTV','295',2,logos_tvp+'295.png')
	xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)
	
def play(url):
	resolved = liveresolver.resolve(url)
	item = xbmcgui.ListItem(path=resolved)
	xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
	
def getCookiesString(cookieJar):
    try:
        cookieString=""
        for index, cookie in enumerate(cookieJar):
            cookieString+=cookie.name + "=" + cookie.value +";"
    except: pass
    #print 'cookieString',cookieString
    return cookieString
def open_url(url,data=None,headers=None, cj=None):
    cookie_handler = urllib2.HTTPCookieProcessor(cj)
    opener = urllib2.build_opener(cookie_handler, urllib2.HTTPBasicAuthHandler(), urllib2.HTTPHandler())
        
    req = urllib2.Request(url)

    req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
    if headers:
        for h in headers:
            req.add_header(h, headers[h])
    response = opener.open(req,data=data)
    link=response.read()
    response.close()
    return link
    
    
def get_treabaAia():
    val=""
    import math
    for d in [5.6
            ,12.1
            ,7.5
            ,3.3
            ,11.8
            ,7
            ,11.6
            ,9
            ,10.7
            ,6.6
            ,3.5
            ,10.1
            ,11.8
            ,7.1
            ,11.5]:
        val +=  chr(int(math.floor(d * 10)));
    return val
import md5
#print 
def generateKey(tokenexpiry):
    return md5.new(tokenexpiry+get_treabaAia()).hexdigest()
print generateKey("1473650167")
def tvplayer(url):
    import re,urllib,json
    watchHtml=open_url('http://tvplayer.com/watch/')
    hashval=urllib.unquote(re.findall('hash = "(.*?)"' ,watchHtml)[0])
    expval=re.findall('exp = "(.*?)"' ,watchHtml)[0]
    keyval=generateKey(expval)
    cj = CookieJar()
    data = urllib.urlencode({'id' : url})
    headers={'Token-Expiry':expval ,'Hash': hashval,'Key':keyval,'Referer':'http://assets.tvplayer.com/web/flash/tvplayer/TVPlayer-DFP-3.swf','X-Requested-With':'ShockwaveFlash/22.0.0.209'}
    retjson=open_url("http://live.tvplayer.com/stream-web-encrypted.php",data=data, headers=headers,cj=cj);
    jsondata=json.loads(retjson)
#    print cj
    url=jsondata["tvplayer"]["response"]["stream"]
    play(url+'|Cookie=%s&User-Agent=Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36&X-Requested-With=ShockwaveFlash/22.0.0.209&Referer=http://tvplayer.com/watch/'%getCookiesString(cj))
    return 
    
    #url='http://api.tvplayer.com/api/v2/stream/live/?id=%s&service=1&platform=website&token=A5roOFiAkvbuD7USnF76j9HbnpZJPFhTeojsN0zaLik=&validate=eyJ0b2tlbiI6IjRjNTdkZTVjOTFkNzJjOGNlZjI2OTNjYTFiMzFhMTJjIiwiZXhwaXJ5IjoiMjAxNi0wOS0xMVQxODowMjoyNCswMDAwIn0=&device=null' % url
    
    #iconimage=""
    #req = urllib2.Request(url)
    #req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
    #response = urllib2.urlopen(req)
    #link=response.read()
    #response.close()

    #pattern = ""
    #matches = plugintools.find_multiple_matches(link,'"tvplayer":(.*?)"drmToken"')
    
    #for entry in matches:
       
    #    url = plugintools.find_single_match(entry,'"stream": "(.+?)",')

    #    play(url)
	
def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param
        
def addLink(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setProperty('fanart_image', fanart)
        liz.setProperty("IsPlayable","true")
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
        return ok

def addDir(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setProperty('fanart_image', fanart)
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok
        
              
params=get_params()
url=None
name=None
mode=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass

print "Mode: "+str(mode)
print "Name: "+str(name)

if mode==None or url==None or len(url)<1:
        print ""
        CATEGORIES()
	
elif mode==1: play(url)
elif mode==2: tvplayer(url)

xbmcplugin.endOfDirectory(int(sys.argv[1]))
