#!/usr/bin/python
# -*- coding: utf-8 -*-
# - ====================================== antizapret ====================================================
import xbmc, xbmcaddon
import time, cookielib, urllib, urllib2, os, sys
__settings__ = xbmcaddon.Addon(id='plugin.video.LostFilm3')
sid_file = os.path.join(xbmc.translatePath('special://temp/'), 'vpn.sid')
cj = cookielib.FileCookieJar(sid_file) 
hr  = urllib2.HTTPCookieProcessor(cj) 

proxy_list=[
	'http://xawos.ovh/index.php?q=',             #Франция
	'http://prx.afkcz.eu/prx/index.php?q=',      #Чехия
	'https://derzeko.de/Proxy/index.php?q=',     #Германия
	'https://dev.chamoun.fr/proxy/index.php?q=', #Франция
]

#	'http://thely.fr/proxy/?q=',                 #Франция
#	'http://www.pitchoo.net/zob_/index.php?q=',  #Франция
#	'http://www.proxy.zee18.info/index.php?q=',  #Великобритания

def test_url(url):
	import urllib2
	url=url.replace('?q=', '')
	try:
		response = urllib2.urlopen(url, timeout=3)
		return response.getcode()
	except:
		return '404'

def mfindal(http, ss, es):
	L=[]
	while http.find(es)>0:
		s=http.find(ss)
		e=http.find(es,s)
		i=http[s:e]
		L.append(i)
		http=http[e+2:]
	return L

def mfind(t,s,e):
	r=t[t.find(s)+len(s):]
	r2=r[:r.find(e)]
	return r2

def GETvpn():
	import httplib
	conn = httplib.HTTPConnection("antizapret.prostovpn.org")
	conn.request("GET", "/proxy.pac", headers={"User-Agent": 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C)'})
	r1 = conn.getresponse()
	data = r1.read()
	conn.close()
	return data

def proxy_update():
	try:
		print 'proxy_update'
		#url='https://antizapret.prostovpn.org/proxy.pac'
		pac=GETvpn()#url)
		prx=pac[pac.find('PROXY ')+6:pac.find('; DIRECT')]
		__settings__.setSetting("proxy_serv", prx)
		__settings__.setSetting("proxy_time", str(time.time()))
	except: 
		print 'except get proxy'

def get_opener():
		try:pt=float(__settings__.getSetting("proxy_time"))
		except:pt=0
		print pt
		if time.time()-pt > 36000: proxy_update()
		prx=__settings__.getSetting("proxy_serv")
		print prx
		if prx.find('http')<0 : prx="http://"+prx
		proxy_support = urllib2.ProxyHandler({"http" : prx})
		opener = urllib2.build_opener(proxy_support, hr)
		#urllib2.install_opener(opener)
		print 'opener ok'
		return opener

def original(url):
	try:
		if '?q=' in url:
			import base64
			url=base64.b64decode(urllib.unquote_plus(url[url.find('?q=')+3:]))
	except: pass
	return url


def convert(url):
	import base64
	try: id=int(__settings__.getSetting("proxy_id"))
	except: id=-1
	try: tm=float(__settings__.getSetting("proxy_tm"))
	except: tm=0
	dt = time.time()-tm
	redir=proxy_list[id]+urllib.quote_plus(base64.b64encode(url))
	if id!=-1: 
		if dt<3600:
			#proxy=proxy_list[id]
			c=test_url(redir)
		else:
			c='200'
	if id<0 or c=='404':
		for id in range (len(proxy_list)):
				proxy=proxy_list[id]
				redir=proxy_list[id]+urllib.quote_plus(base64.b64encode(url))
				c=test_url(redir)
				if c!='404': 
					__settings__.setSetting("proxy_id", str(id))
					__settings__.setSetting("proxy_tm", str(time.time()))
					break
	
	#sign=base64.b64encode(url)
	#redir=proxy_list[id]+urllib.quote_plus(sign)
	
	#print '=== convert ==='
	#print redir
	return redir


def decoder(hp, id=0):
	import base64, urllib
	id=int(__settings__.getSetting("proxy_id"))
	if id=='': id=0
	r=''
	L=hp.splitlines()
	proxy = proxy_list[id]
	for h in L:
		if proxy not in h:
			if 'https:' in proxy: alturl = proxy.replace('https:', 'http:')
			else : alturl = proxy.replace('http:', 'https:')
			if alturl in h: proxy = alturl
		if proxy in h:
			L2=mfindal(h, proxy, '"')
			for i in L2:
				try:
					url=base64.b64decode(urllib.unquote_plus(i.replace(proxy,'')))
					#if '%22%20style=' in url:
					#	url='http://www.lostfilm.tv/series/'+base64.b64decode(mfind(url,'/series/','%22%20style='))
					print url
					h=h.replace(i, url)
				except:
					pass
					print 'ERR'
					print i
			r+=h+'\n'
		else:
			r+=h+'\n'
	#print hp
	return r
