import urllib, urllib2
import sys, re, os, json, random, string, base64, hashlib, pyaes
import xbmcplugin, xbmcgui, xbmcaddon, xbmc
import net
from urlparse import parse_qsl

addonID = "plugin.video.f3ktv"
fanart = xbmc.translatePath(os.path.join('special://home/addons/' + addonID, 'fanart.jpg'))
icon = xbmc.translatePath(os.path.join('special://home/addons/' + addonID, 'icon.png'))
artpath = xbmc.translatePath(os.path.join('special://home/addons/' + addonID + '/resources/art/'))
dialog = xbmcgui.Dialog()
selfAddon = xbmcaddon.Addon(id=addonID)
net = net.Net()
username = '-1'

def RefreshResources(resources):
#	print Fromurl
	pDialog = xbmcgui.DialogProgress()
	ret = pDialog.create('XBMC', 'checking Updates...')
	totalFile=len(resources)
	fileno=0
	import hashlib
	updated=False
	try:
		for rfile in resources:
			if pDialog.iscanceled(): return
			progr = (fileno*80)/totalFile
			fname = rfile[0]
			fileToDownload = rfile[1]
			addonPath = xbmcaddon.Addon().getAddonInfo("path")
			addonversion =xbmcaddon.Addon().getAddonInfo("version")
			fileHash=hashlib.md5(fileToDownload+addonversion).hexdigest()
			lastFileTime=selfAddon.getSetting( "Etagid"+fileHash)  
			if lastFileTime=="": lastFileTime=None
			resCode=200
			#print fileToDownload
			eTag=None		 
			try:
				req = urllib2.Request(fileToDownload)
				req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')

				if lastFileTime:
					req.add_header('If-None-Match',lastFileTime)
				response = urllib2.urlopen(req)
				resCode=response.getcode()
				if resCode<>304:
					try:
						eTag=response.info().getheader('Etag')
					except: pass
					data=response.read()
			except Exception as e: 
				s = str(e)
				if 'Not Modified'.lower() in s.lower(): resCode=304
				data=''
			if ('Exec format error: exec' in data or 'A file permissions error has occurred' in data) and 'xbmcplugin' not in data:
				data=''

			if len(data)>0:
				with open(os.path.join(addonPath, fname), "wb") as filewriter:
					filewriter.write(data)
					updated=True
					if eTag:
						selfAddon.setSetting( id="Etagid"+fileHash ,value=eTag)	   
				pDialog.update(20+progr, 'imported ...'+fname)
			elif resCode==304:
				pDialog.update(20+progr, 'No Change.. skipping.'+fname)
			else:			 
				pDialog.update(20+progr, 'Failed..zero byte.'+fname)
			fileno+=1
	except: print traceback.print_exc()
	pDialog.close()
	return updated


# main function

def main():
	addDir('All Channels','0',1,artpath+'all.PNG',fanart)
	addDir('Entertainment','1',1,artpath+'ent.PNG',fanart)
	addDir('Movies','2',1,artpath+'mov.PNG',fanart)
	addDir('Music','3',1,artpath+'mus.PNG',fanart)
	addDir('News','4',1,artpath+'news.PNG',fanart)
	addDir('Sports','5',1,artpath+'sport.PNG',fanart)
	addDir('Documentary','6',1,artpath+'doc.PNG',fanart)
	addDir('Kids Corner','7',1,artpath+'kids.PNG',fanart)
	addDir('Food','8',1,artpath+'food.PNG',fanart)
	addDir('Religious','9',1,artpath+'rel.PNG',fanart)
	addDir('USA Channels','10',1,artpath+'us.PNG',fanart)
	addDir('Others','11',1,artpath+'others.PNG',fanart)
	xbmc.executebuiltin('Container.SetViewMode(500)')

# Getting token

def getToken(url, username):
	if 'get_valid_link' in url:
		s = "uktvnow-token--_|_-http://uktvnow.net/app2/v3/get_valid_link-uktvnow_token_generation-"+username+"-_|_-123456_uktvnow_654321-_|_-uktvnow_link_token"
	else:
		s = "uktvnow-token--_|_-"+url+"-uktvnow_token_generation-"+username+"-_|_-123456_uktvnow_654321"
	return hashlib.md5(s).hexdigest()

# Getting channels
	
def getChannels():
	token=getToken('http://uktvnow.net/app2/v3/get_all_channels',username)
	headers={'User-Agent':'USER-AGENT-UKTVNOW-APP-V2','app-token':token}
	postdata={'username':username}
	channels = net.http_POST('http://uktvnow.net/app2/v3/get_all_channels',postdata, headers).content
	channels = channels.replace('\/','/')
	match=re.compile('"pk_id":"(.+?)","channel_name":"(.+?)","img":"(.+?)","http_stream":"(.+?)","rtmp_stream":"(.+?)","cat_id":"(.+?)"').findall(channels)
	return match

# Showing the channels

def showChannels(url):
	match = getChannels()
	for channelid,name,iconimage,stream1,stream2,cat in match:
		thumb='https://app.uktvnow.net/'+iconimage+'|User-Agent=Dalvik/2.1.0 (Linux; U; Android 6.0.1; SM-G935F Build/MMB29K)'	 
		if url=='0':addLink(name,'url',2,thumb,fanart,channelid)
		if cat==url:addLink(name,'url',2,thumb,fanart,channelid)
	xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_VIDEO_TITLE)
	xbmc.executebuiltin('Container.SetViewMode(500)')

# Getting the streams

def getStreams(name, iconimage, channelid):
	UAToken = getToken('http://uktvnow.net/app2/v3/get_user_agent', username)
	headers={'User-Agent':'USER-AGENT-UKTVNOW-APP-V2','app-token':UAToken}
	postdata={'User-Agent':'USER-AGENT-UKTVNOW-APP-V2','app-token':UAToken,'version':'5.7'}
	UAPage = net.http_POST('http://uktvnow.net/app2/v3/get_user_agent',postdata, headers).content
	UAString=re.compile('"msg":{".+?":"(.+?)"}}').findall(UAPage)[0]
	UA=UAString
	playlist_token = getToken('http://uktvnow.net/app2/v3/get_valid_link', username+channelid)
	postdata = {'useragent':UA,'username':username,'channel_id':channelid,'version':'5.7'}	
	headers={'User-Agent':'USER-AGENT-UKTVNOW-APP-V2','app-token':playlist_token}
	channels = net.http_POST('http://uktvnow.net/app2/v3/get_valid_link',postdata, headers).content
	match=re.compile('"channel_name":"(.+?)","img":".+?","http_stream":"(.+?)","rtmp_stream":"(.+?)"').findall(channels)
	if len(match) == 0: return
	match = match[-1]
	ok=True
	liz=xbmcgui.ListItem(name, iconImage=iconimage,thumbnailImage=iconimage); liz.setInfo( type="Video", infoLabels={ "Title": name } )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
	played = False
	try:
		import uktvplayer
		played = uktvplayer.play(liz, [{"name": match[0], "http_stream": match[1], "rtmp_stream": [1]]}])     
	except: print traceback.print_exc()
		if not played:
			if RefreshResources([('default.py','https://gist.githubusercontent.com/juTTeruk/ebd321dce1b52c8b39aa/raw/default.py')]):
				dialog = xbmcgui.Dialog()
				ok = dialog.ok('XBMC', 'Updated files dyamically, restart the plugin, just in case!')           
				print 'Updated files'
		return
	return ok

# Decrypting the URL

def decryptURL(url):
	magic="1579547dfghuh,difj389rjf83ff90,45h4jggf5f6g,f5fg65jj46,gr04jhsf47890$93".split(',')
	#decryptor = pyaes.new(magic[1], pyaes.MODE_CBC, IV=magic[4])
	decryptor = pyaes.new("2s7Oc5*D13kljsd^", pyaes.MODE_CBC, IV="J842fou5TZ!toX8b")
	url= decryptor.decrypt(url.decode("hex")).split('\0')[0]
	return url


# Utilities

# Add link

def addLink(name, url, mode, iconImage, fanart, channelID=''):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&channelid="+str(channelID)+"&iconimage="+urllib.quote_plus(iconImage)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconImage)
	liz.setInfo( type="Video", infoLabels={ "Title": name, 'plot': channelID } )
	liz.setProperty('fanart_image', fanart)
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
	return ok

# Add directory

def addDir(name, url, mode, iconImage, fanart, channelID=''):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&channelid="+str(channelID)+"&iconimage="+urllib.quote_plus(iconImage)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconImage)
	liz.setInfo( type="Video", infoLabels={ "Title": name, 'plot': channelID } )
	liz.setProperty('fanart_image', fanart)
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
	return ok

# Parse params

def parseParams():
	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 setView(content, viewType):
	if content:
		xbmcplugin.setContent(int(sys.argv[1]), content)
	if selfAddon.getSetting('auto-view')=='true':
		xbmc.executebuiltin("Container.SetViewMode(%s)" % selfAddon.getSetting(viewType) )
	
#params = parseParams()
params = dict(parse_qsl(sys.argv[2][1:]))
params = params if params else {}
url = None
name = None
mode = None
iconImage = None
channelID = None

print str(params) + " asd"
try:
	url = urllib.unquote_plus(params["url"])
except Exception as e:
	print e
	pass

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

try:
	mode = int(params["mode"])
except Exception as e:
	print e
	pass

try:
	iconImage = urllib.unquote_plus(params["iconimage"])
except:
	pass

try:
	channelID = urllib.unquote_plus(params["channelid"])
except:
	pass

if mode != None:
	print "ads: " + str(mode)

if mode == None or url == None or len(url) < 1:
	main()
elif mode == 1:
	showChannels(url)
elif mode == 2:
	getStreams(name, iconImage, channelID)
xbmcplugin.endOfDirectory(int(sys.argv[1]))