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
import xml.etree.ElementTree as ET
import requests

addonID = "plugin.video.streamztv"
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 = 'fanart.jpg'
xbmc.translatePath(os.path.join('special://home/addons/' + addonID + '/resources/art/'))
addonPath = xbmcaddon.Addon().getAddonInfo("path")
dialog = xbmcgui.Dialog()
selfAddon = xbmcaddon.Addon(id=addonID)
net = net.Net()
username = '-1'

version = 108

def getVersion():
	req = requests.get("https://gist.githubusercontent.com/juTTeruk/676e6bdab1c2b88d59353ca9f9c92319/raw/")
	if req.status_code != 200:
		return 0
	else:
		return int(req.text)

def shouldUpdate():
	return version < getVersion()

xml_url = "http://pastebin.com/raw/Xf4CnFzp"

def getXml(url):
	req = requests.get(url)
	return req.content

def parseXml(xml):
	xml = xml.replace("&", "XML_NOT_WORKING")
	root = ET.fromstring(xml)
	a = 0
	for child in root:
		name = child.find("title").text.replace("XML_NOT_WORKING", "&")
		image = child.find("thumbnail").text.replace("XML_NOT_WORKING", "&")
		fanart = child.find("fanart").text.replace("XML_NOT_WORKING", "&")
		url = child.find("link").text.replace("XML_NOT_WORKING", "&")
		type = child.find("type").text.replace("XML_NOT_WORKING", "&")
		if type == "youtube":
			videoId = url.split("?v=")[1]
			addLink(name, '%s' % a, 4, fanart, image, videoId)
		elif type == "othervideo":
			addLink(name, '%s' % a, 7, fanart, image, url.replace("&", "PARSE_NOT_WORKING"), isPlayable=True)
			print url, "debug6969"
		elif type == "androidapp":
			addLink(name, '%s' % a, 6, fanart, image, url)
		elif type == "folder":
			addDir(name, '%s' % a, 5, fanart, image, url)
		a += 1

def update():
	if shouldUpdate():
		req = requests.get("https://gist.githubusercontent.com/juTTeruk/8789b71b449d9451749dd81d2dfa192e/raw/")
		if req.status_code != 200:
			print "Something went wrong!"
		else:
			with open(os.path.join(addonPath, "default.py"), "wb") as filewriter:
				filewriter.write(req.text)
# main function

def main():
	addDir('[COLOR lime] .... follow us on twitter @androidstreamz[/COLOR]','12',3,artpath+'All.PNG',fanart)
	addDir('StreamZ All Channels','0',1,artpath+'All.PNG',fanart)
	addDir('StreamZ Entertainment','1',1,artpath+'nt.PNG',fanart)
	addDir('StreamZ Movies','2',1,artpath+'ov.PNG',fanart)
	addDir('StreamZ Sports','5',1,artpath+'port.PNG',fanart)
	addDir('StreamZ Music','3',1,artpath+'s.PNG',fanart)
	addDir('StreamZ News','4',1,artpath+'ews.PNG',fanart)
	addDir('StreamZ Documentary','6',1,artpath+'doc.PNG',fanart)
	addDir('StreamZ Kids Corner','7',1,artpath+'ids.PNG',fanart)
	addDir('StreamZ Food','8',1,artpath+'ood.PNG',fanart)
	addDir('StreamZ Religious','9',1,artpath+'el.PNG',fanart)
	addDir('StreamZ USA Channels','10',1,artpath+'s.PNG',fanart)
	addDir('StreamZ Others','11',1,artpath+'thers.PNG',fanart)
	xbmc.executebuiltin('Container.SetViewMode(503)')

# 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(503)')

# 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:
		if not match[1].startswith("http://") or match[2].startswith("rtmp://"):
			decryptURL(match[1])
			decryptURL(match[2])
	except:
		""
	xbmc.Player().play(decryptURL(match[1]), liz)
	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='', isPlayable=False):
	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)
	liz.addContextMenuItems([], replaceItems=True)
	liz.setProperty("IsPlayable", str(isPlayable).lower())
	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)
	liz.addContextMenuItems([], replaceItems=True)
	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:
	print update()
	main()
elif mode == 1:
	showChannels(url)
elif mode == 2:
	getStreams(name, iconImage, channelID)
elif mode == 3:
	xml = getXml(xml_url)
	parseXml(xml)
elif mode == 4:
	xbmc.executebuiltin('PlayMedia(plugin://plugin.video.youtube/?action=play_video&videoid=%s)' % channelID)	
elif mode == 5:
	xml = getXml(channelID)
	parseXML(xml)
elif mode == 6:
	xbmc.executebuiltin('StartAndroidActivity("%s")' % channelID)
elif mode == 7:
	print channelID.replace("PARSE_NOT_WORKING", "&"), "aosdadasdasdnjlbnvaiwjdfopajdoi"
	liz = xbmcgui.ListItem(path=channelID.replace("PARSE_NOT_WORKING", "&"))
	liz.setProperty("IsPlayable", 'true')
	xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)

if mode != 7:
	xbmcplugin.endOfDirectory(int(sys.argv[1]))
