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

proxy_list=[
	'http://www.pitchoo.net/zob_/index.php?q=',  #Франция
	'http://thely.fr/proxy/?q=',                 #Франция
	'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://www.proxy.zee18.info/index.php?q=',  #Великобритания
]


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 convert(url):
	try: id=int(__settings__.getSetting("proxy_id"))
	except: id=0
	import base64
	sign=base64.b64encode(url)
	redir=proxy_list[id]+urllib.quote_plus(sign)
	return redir

def decoder(hp, id=0):
	try: id=int(__settings__.getSetting("proxy_id"))
	except: id=0
	import base64
	L=mfindal(hp, proxy_list[id], '"')
	for i in L:
		try:
			#print i
			url=base64.b64decode(i.replace(proxy_list[id],'').replace('%3D','='))
			#print url
			hp=hp.replace(i, url)
		except:
			pass
			#print i
	#print hp
	return hp
