# -*- coding: utf-8 -*-	
import xbmc,xbmcgui,xbmcaddon	
import six	
from six.moves import urllib_parse	
if six.PY3:	
	LOGNOTICE = xbmc.LOGINFO	
  #  from resources.lib.cmf3 import parseDOM	
else:	
	LOGNOTICE = xbmc.LOGNOTICE	
#	from resources.lib.cmf2 import parseDOM	
	
import json	
import re,os	
 
import requests	

sess = requests.Session()	
 
UA = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0'	
	
addon = xbmcaddon.Addon(id='plugin.video.ekstraklasa')	
	
username = addon.getSetting('username')	
password = addon.getSetting('password')	
sessionToken = addon.getSetting('sessionToken')  

deviceid = addon.getSetting('deviceid')  
if not deviceid:
	import uuid
	deviceid = str(uuid.uuid4())+'_WEB'	
	addon.setSetting("deviceid",deviceid) 
  
jakwid = addon.getSetting('jakwid')	
jakwid2 = addon.getSetting('jakwid2')	
	
	
headers = {	
	'User-Agent': UA,	
	'Accept': 'application/json',	
	'Accept-Language': 'pl,en-US;q=0.7,en;q=0.3',	
	'Referer': 'https://www.ekstraklasa.tv/',	
	'Content-Type': 'application/json',	
	'Authorization': 'Bearer %s'%sessionToken,	
	'Origin': 'https://www.ekstraklasa.tv',	
	'DNT': '1',	
}	
  

v3base = 'https://exposure.api.redbee.live/v3/{}'#customer/Ekstraklasa/businessunit/EkstraklasaTV/auth/login
v2base = 'https://exposure.api.redbee.live/v2/{}'

#'https://exposure.api.redbee.live/v3/customer/Ekstraklasa/businessunit/EkstraklasaTV/auth/login


  
import threading	
	
class Thread(threading.Thread):	
	def __init__(self, target, *args):	
		self._target = target	
		self._args = args	
		self.result = ''	
		threading.Thread.__init__(self)	
			
	def run(self):	
		self.result = self._target(*self._args)	
	
	
def Login():	
	url = v3base.format('customer/Ekstraklasa/businessunit/EkstraklasaTV/auth/login')
	if username and password:   
		

			 #deviceid = addon.getSetting('deviceid') 
		#data={	
		#	"client_id": clid,	
		#	"client_secret": clsecret,	
		#	"grant_type": "password",	
		#	"username": username,	
		#	"password": password,	
		#}   
		#deviceid = addon.getSetting('deviceid') 
		data={
			"username": username, 
			"password": password,  
			"device": {
				"deviceId": deviceid,
				"width": 1366,
				"height": 369,
				"type": "WEB",
				"name": "Windows 7"
			},
			"informationCollectionConsentGivenNow": False
			}



		hd = {
			'Host': 'exposure.api.redbee.live',
			'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0',
			'accept': 'application/json, text/plain, */*',
			'accept-language': 'pl,en-US;q=0.7,en;q=0.3',
			'content-type': 'application/json',
			'origin': 'https://www.ekstraklasa.tv',
			'referer': 'https://www.ekstraklasa.tv/'}
			
  
		response = requests.post(url,json=data,headers=hd,verify=False,).json()  
	
	
		
		try:	
			sessionToken = response.get("sessionToken",None)  
			addon.setSetting("sessionToken",sessionToken)	
			return True	
		except:	
			xbmcgui.Dialog().notification('[B]Nieudane logowanie[/B]', 'Sprawdź login i hasło w ustawieniach wtyczki.',xbmcgui.NOTIFICATION_INFO, 6000)	
			return False	
	xbmcgui.Dialog().notification('[B]Nieudane logowanie[/B]', 'Sprawdź login i hasło w ustawieniach wtyczki.',xbmcgui.NOTIFICATION_INFO, 6000)	
	return False	
	
def ListCategory():	
	#out=[]	
   # /api/internal/customer/Ekstraklasa/businessunit/EkstraklasaTV/component/478bff51-c17d-4c5a-a857-433647b73031?deviceGroup=web&locale=pl
	out=[{'img': '',
		'plot': '',
		'title': 'Mecze',
		'url': 'https://www.ekstraklasa.tv/api/internal/customer/Ekstraklasa/businessunit/EkstraklasaTV/component/dcf33750-3ace-43da-b836-e2d2f22bc8b1?deviceGroup=web&locale=pl'},
		{'img': '',
		'plot': '',
		'title': 'Najnowsze skróty',
		'url': 'https://www.ekstraklasa.tv/api/internal/customer/Ekstraklasa/businessunit/EkstraklasaTV/component/478bff51-c17d-4c5a-a857-433647b73031?deviceGroup=web&locale=pl'},	
		{'img': '',
		'plot': '',
		'title': 'Ekstra gole / akcje / parady',
		'url': 'https://www.ekstraklasa.tv/api/internal/customer/Ekstraklasa/businessunit/EkstraklasaTV/component/bd6f6088-98d0-4498-ae07-f0d3c2b21f77?deviceGroup=web&locale=pl'},	
	
		#{'img': '',
	   #'plot': '',
	   #'title': 'Oficjalny magazyn ekstraklasy',
	   #'url': 'https://www.ekstraklasa.tv/api/internal/customer/Ekstraklasa/businessunit/EkstraklasaTV/component/741ce11f-bac6-4ccb-b4d0-df81b1293fc1?deviceGroup=web&locale=pl'},	

		{'img': '',
		'plot': '',
		'title': 'Fantasy Ekstraklasa',
		'url': 'https://www.ekstraklasa.tv/api/internal/customer/Ekstraklasa/businessunit/EkstraklasaTV/component/3dc49cda-187f-40a4-84d7-1c398aa224eb?deviceGroup=web&locale=pl'},	
	
	
	
		{'img': '',
		'plot': '',
		'title': 'Top 5',
		'url': 'https://www.ekstraklasa.tv/api/internal/customer/Ekstraklasa/businessunit/EkstraklasaTV/component/79a09fac-b139-4c6e-b16a-f7c01067226a?deviceGroup=web&locale=pl'},	
	
		{'img': '',
		'plot': '',
		'title': 'Kompilacje',
		'url': 'https://www.ekstraklasa.tv/api/internal/customer/Ekstraklasa/businessunit/EkstraklasaTV/component/92988243-f44e-47b3-ad15-10e89bebea55?deviceGroup=web&locale=pl'},	
	
		{'img': '',
		'plot': '',
		'title': 'Top 10',
		'url': 'https://www.ekstraklasa.tv/api/internal/customer/Ekstraklasa/businessunit/EkstraklasaTV/component/6268e7a7-907e-4319-83c1-904d8feb4a58?deviceGroup=web&locale=pl'},	
	
		{'img': '',
		'plot': '',
		'title': 'Kluby',
		'url': 'https://www.ekstraklasa.tv/api/internal/customer/Ekstraklasa/businessunit/EkstraklasaTV/page/ed15d161-9f59-47dd-b001-e3c6efb99329?deviceGroup=web&locale=pl'},	
	

	
	
		{'img': '',
		'plot': '',
		'title': 'VOD',
		'url': 'https://www.ekstraklasa.tv/api/internal/customer/Ekstraklasa/businessunit/EkstraklasaTV/component/e21efa5f-5f65-4602-9f43-438df75abbc3?deviceGroup=web&locale=pl'},	]
	
	
	
	return out	
def convtime(tt):	
	import datetime	
	import time	

	modified_date=''
	if tt:	
		tt = re.sub('\.\d+Z','',tt)	
		try:	
			my_date = datetime.datetime.strptime(tt, '%Y-%m-%dT%H:%M:%SZ')	

		except TypeError:	
			my_date = datetime.datetime(*(time.strptime(tt, '%Y-%m-%dT%H:%M:%SZ')[0:6]))	

		modified_date = my_date + datetime.timedelta(hours=1)	
		try:
			modified_date = modified_date.strftime("%d.%m %H:%M")
		except:
			modified_date = ''
		#modified_date = ' [COLOR orange]('+modified_date+')[/COLOR]'
	mod_data = str(modified_date)	
	
	return ' [COLOR orange]('+mod_data+')[/COLOR]' if mod_data else ''
	
def getContent(url,type='skroty',page=1, category=7,**args):	
	out=[]	

	response = requests.get(url, headers=headers,verify=False) .json()
	
	assets = response.get('assets',None)
	components = response.get('components',None)
	if assets:
		for asset in assets:
			cv=''
	
			t = asset.get('title',None)
			start = convtime(asset.get('startTime',None))
			if t == '':
				tags  = asset.get('tags',None)
				if tags:
					t =  ' - '.join([x.get('title') for x in tags if x.get('title').lower()!='mecz'])
				t = t+start			
			i = asset.get('images',None)[0].get('url',None)
			h1 = asset.get('action',None).get('assetId',None)
			h = 'https://exposure.api.redbee.live/v2/customer/Ekstraklasa/businessunit/EkstraklasaTV/entitlement/{}/play'.format(str(h1))
			out.append({'url':h,'title':t,'img':i,'plot':'','code':''})  
	elif components:
		for asset in components:

			internalUrl = asset.get('internalUrl',None)
			url2 = 'https://www.ekstraklasa.tv'+internalUrl
			response = requests.get(url2, headers=headers,verify=False) .json()
			img = response.get("images", None)[0].get("url", None)
			action = response.get("action", None)
			if not action:
				continue
			url3 = 'https://www.ekstraklasa.tv'+action.get('internalUrl',None)
			response = requests.get(url3, headers=headers,verify=False) .json()
			t = response.get("title", None)
			components = response.get("components", None)
			href = ''
			for comp in components:
				if comp.get("type", None) == 'carousel':
					href = 'https://www.ekstraklasa.tv'+comp.get("internalUrl", None)
					break

			out.append({'url':href,'title':t,'img':img,'plot':'','code':'','mud':'site'})  
		
		
	np=False	
	pp=False  
	
	
	
	return out,(pp,np)	
	
		
def crProxy():	
	headers = {	
		'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0',	
		'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',	
		'Accept-Language': 'pl,en-US;q=0.7,en;q=0.3',	
		'Connection': 'keep-alive',	
		'Referer': 'https://proxyscrape.com/free-proxy-list',	
		'Upgrade-Insecure-Requests': '1',	
	}	
		
	params = (	
		('request', 'getproxies'),	
		('proxytype', 'http'),	
		('timeout', '10000'),	
		('country', 'US'),	
		('ssl', 'all'),	
		('anonymity', 'all'),	
	)	
		
	response = requests.get('https://api.proxyscrape.com/', headers=headers, params=params).text	
	if six.PY3:	
		response= response.encode(encoding='utf-8', errors='strict')	
		
		
	linie = response.splitlines()	
	linie = response.splitlines()	
	proxies=['%s'%(x) for x in linie]	
	return proxies	
		
def searchproxy(url):	
	stream_url=''	
	
	timeout=15	
	dialog  = xbmcgui.DialogProgress()	
	dialog.create('Szukam darmowych serwerów proxy ...')	
	proxies=crProxy()	
	dialog.create('Znalazłem %d serwerów proxy'%len(proxies))	
		
	proxies = [Thread(getVideosProxy, url,proxy,timeout) for proxy in proxies ]	
	[i.start() for i in proxies]	
	dialog.update(0,'Sprawdzam %d serwery ... '%(len(proxies)))	
	while any([i.isAlive() for i in proxies]):	
		xbmc.sleep(1000)	
		done = [t for t in proxies if not t.isAlive()]	
		dialog.update(int(1.0*len(done)/len(proxies)*100),'Sprawdzam, negatywnie odpowiedziało: %d, proszę czekać'%(len(done)))	
		for t in done:	
			stream_url = t.result	
			if stream_url:	
				break	
			else:	
				stream_url=''	
		if stream_url or dialog.iscanceled():	
			break	
	dialog.close()	
	return {"http": t._args[1], "https": t._args[1]}	   
	
def getVideosProxy(url,proxy,timeout):	
		
	try:	
		proxy = {"http": proxy, "https": proxy}	
		response = sess.get(url, headers=headers,proxies=proxy,verify=False,timeout=timeout).json()	
		if response.has_key('message'):	
			aa = response['message']	
			if 'geo-blocked' in aa:	
				return False	
		else:	
			return True	
	
	except:	
		return False	
			
def getVideos(url):	
	
	
	zagr = addon.getSetting('zagrproxy')	
	out=[]	
	response = requests.get(url, headers=headers,verify=False).json()   
	
	formaty = response.get('formats',None)
	url =''
	lic_url =''
	
	try:
		for ff in formaty:
			if ff.get('format',None) == 'DASH':
				url = ff.get('mediaLocator',None)
				if 'drm' in ff:
					lic_url = ff.get('drm',None).get('com.widevine.alpha',None).get('licenseServerUrl', None)
				break
		
		
		pth=url+'|User-Agent='+urllib_parse.quote(UA)+'|DASH'#+'&Cookie='+ab	
		if lic_url:
			pth +='|licurl='+lic_url
		out.append({'url':pth,'msg':'','resolved':True})	
	except:
		pass
	return out	
	
		
def getMain():	
	logged = Login()	
	out=[]	
	if logged:	
		out = ListCategory()	
	return out	
	
def unicodePLchar(txt):	
	s='JiNcZCs7'	
	txt = re.sub(s.decode('base64'),'',txt)	
	txt = re.sub('&quot;','"',txt)	
	txt = re.sub('&.*;','',txt)	
	txt = txt.replace('&nbsp;','')	
	txt = txt.replace('&lt;br/&gt;',' ')	
	txt = txt.replace('&ndash;','-')	
	txt = txt.replace('&quot;','"').replace('&amp;quot;','"')	
	txt = txt.replace('&oacute;','ó').replace('&Oacute;','Ó')	
	txt = txt.replace('&amp;oacute;','ó').replace('&amp;Oacute;','Ó')	
	txt = txt.replace('&amp;','&')	
	txt = txt.replace('\u0105','ą').replace('\u0104','Ą')	
	txt = txt.replace('\u0107','ć').replace('\u0106','Ć')	
	txt = txt.replace('\u0119','ę').replace('\u0118','Ę')	
	txt = txt.replace('\u0142','ł').replace('\u0141','Ł')	
	txt = txt.replace('\u0144','ń').replace('\u0144','Ń')	
	txt = txt.replace('\u00f3','ó').replace('\u00d3','Ó')	
	txt = txt.replace('\u015b','ś').replace('\u015a','Ś')	
	txt = txt.replace('\u017a','ź').replace('\u0179','Ź')	
	txt = txt.replace('\u017c','ż').replace('\u017b','Ż')	
	return txt	
