#!/usr/bin/python
# -*- coding: utf-8 -*-

import httplib
#import re
#import sys
import os
#import Cookie

import string, xbmc, xbmcgui, xbmcplugin, xbmcaddon
#-------------------------------
import urllib, urllib2, time, random
#from time import gmtime, strftime 
#from urlparse import urlparse 

import HTMLParser 
hpar = HTMLParser.HTMLParser()
#-----------------------------------------
import socket
socket.setdefaulttimeout(50)

icon = ""

siteUrl = 'kinozal.tv'
httpSiteUrl = 'http://' + siteUrl

__settings__ = xbmcaddon.Addon(id='plugin.video.KinoPoisk.ru')
def unlock(url):
	url='http://127.0.0.1:8095/proxy/'+url
	return url

# - ====================================== antizapret ====================================================
import time, cookielib
sid_file = os.path.join(xbmc.translatePath('special://temp/'), 'vpn.sid')
cj = cookielib.FileCookieJar(sid_file) 
hr  = urllib2.HTTPCookieProcessor(cj) 
Lthread=[]

'''
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'

if __settings__.getSetting("antizapret") == "true":
	try:
		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 'antizapret ok'
	except:
		print 'except set proxy'
		opener = urllib2.build_opener(hr) 
		urllib2.install_opener(opener)
else:
		opener = urllib2.build_opener(hr) 
		urllib2.install_opener(opener)
'''

def convert(url):
	import base64
	sign=base64.b64encode(url)
	redir='http://www.proxy.zee18.info/index.php?q='+urllib.quote_plus(sign)
	return redir


def ru(x):return unicode(x,'utf8', 'ignore')
def xt(x):return xbmc.translatePath(x)
def rt(x):#('&#39;','’'), ('&#145;','‘')
	L=[('&quot;','"'), ('&amp;',"&"),('&#133;','…'),('&#38;','&'),('&#34;','"'), ('&#39;','"'), ('&#145;','"'), ('&#146;','"'), ('&#147;','“'), ('&#148;','”'), ('&#149;','•'), ('&#150;','–'), ('&#151;','—'), ('&#152;','?'), ('&#153;','™'), ('&#154;','s'), ('&#155;','›'), ('&#156;','?'), ('&#157;',''), ('&#158;','z'), ('&#159;','Y'), ('&#160;',''), ('&#161;','?'), ('&#162;','?'), ('&#163;','?'), ('&#164;','¤'), ('&#165;','?'), ('&#166;','¦'), ('&#167;','§'), ('&#168;','?'), ('&#169;','©'), ('&#170;','?'), ('&#171;','«'), ('&#172;','¬'), ('&#173;',''), ('&#174;','®'), ('&#175;','?'), ('&#176;','°'), ('&#177;','±'), ('&#178;','?'), ('&#179;','?'), ('&#180;','?'), ('&#181;','µ'), ('&#182;','¶'), ('&#183;','·'), ('&#184;','?'), ('&#185;','?'), ('&#186;','?'), ('&#187;','»'), ('&#188;','?'), ('&#189;','?'), ('&#190;','?'), ('&#191;','?'), ('&#192;','A'), ('&#193;','A'), ('&#194;','A'), ('&#195;','A'), ('&#196;','A'), ('&#197;','A'), ('&#198;','?'), ('&#199;','C'), ('&#200;','E'), ('&#201;','E'), ('&#202;','E'), ('&#203;','E'), ('&#204;','I'), ('&#205;','I'), ('&#206;','I'), ('&#207;','I'), ('&#208;','?'), ('&#209;','N'), ('&#210;','O'), ('&#211;','O'), ('&#212;','O'), ('&#213;','O'), ('&#214;','O'), ('&#215;','?'), ('&#216;','O'), ('&#217;','U'), ('&#218;','U'), ('&#219;','U'), ('&#220;','U'), ('&#221;','Y'), ('&#222;','?'), ('&#223;','?'), ('&#224;','a'), ('&#225;','a'), ('&#226;','a'), ('&#227;','a'), ('&#228;','a'), ('&#229;','a'), ('&#230;','?'), ('&#231;','c'), ('&#232;','e'), ('&#233;','e'), ('&#234;','e'), ('&#235;','e'), ('&#236;','i'), ('&#237;','i'), ('&#238;','i'), ('&#239;','i'), ('&#240;','?'), ('&#241;','n'), ('&#242;','o'), ('&#243;','o'), ('&#244;','o'), ('&#245;','o'), ('&#246;','o'), ('&#247;','?'), ('&#248;','o'), ('&#249;','u'), ('&#250;','u'), ('&#251;','u'), ('&#252;','u'), ('&#253;','y'), ('&#254;','?'), ('&#255;','y'), ('&laquo;','"'), ('&raquo;','"'), ('&nbsp;',' ')]
	for i in L:
		x=x.replace(i[0], i[1])
	return x

def mfindal(http, ss, es):
	L=[]
	while http.find(es)>0:
		s=http.find(ss)
		e=http.find(es)
		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 rulower(str):
	str=str.strip()
	str=xt(str).lower()
	str=str.replace('Й','й')
	str=str.replace('Ц','ц')
	str=str.replace('У','у')
	str=str.replace('К','к')
	str=str.replace('Е','е')
	str=str.replace('Н','н')
	str=str.replace('Г','г')
	str=str.replace('Ш','ш')
	str=str.replace('Щ','щ')
	str=str.replace('З','з')
	str=str.replace('Х','х')
	str=str.replace('Ъ','ъ')
	str=str.replace('Ф','ф')
	str=str.replace('Ы','ы')
	str=str.replace('В','в')
	str=str.replace('А','а')
	str=str.replace('П','п')
	str=str.replace('Р','р')
	str=str.replace('О','о')
	str=str.replace('Л','л')
	str=str.replace('Д','д')
	str=str.replace('Ж','ж')
	str=str.replace('Э','э')
	str=str.replace('Я','я')
	str=str.replace('Ч','ч')
	str=str.replace('С','с')
	str=str.replace('М','м')
	str=str.replace('И','и')
	str=str.replace('Т','т')
	str=str.replace('Ь','ь')
	str=str.replace('Б','б')
	str=str.replace('Ю','ю')
	return str

def lower(s):
	try:s=s.decode('utf-8')
	except: pass
	try:s=s.decode('windows-1251')
	except: pass
	s=s.lower().encode('utf-8')
	return s

def filtr(title, info):
	try: 
		if info['studio'] == 'Россия': RUS=True
		else: RUS=False
	except: RUS=False
	
	try:    tor_title=title.encode('utf-8').replace("«",'').replace("»",'').replace('"', '').replace("'", '').replace("`", '')
	except: tor_title=title.replace("«",'').replace("»",'').replace('"', '').replace("'", '').replace("`", '')
	
	ru_title=xt(info['title']).replace("«",'').replace("»",'').replace('"', '').replace("'", '').replace("`", '')
	en_title=info['originaltitle'].replace("«",'').replace("»",'').replace('"', '').replace("'", '').replace("`", '')
	
	year=str(info['year'])
	try:year2=str(int(info['year'])+1)
	except:year2=year
	
	if lower(ru_title) in lower(tor_title) or ru_title in tor_title:
		if RUS:
			if '/ РУ /' in tor_title: return True
			else: return False
		else:
			return True
	else: 
		return False


def GET(target, referer='', post=None):
	#print target
	if __settings__.getSetting("antizapret") == "true": target = unlock(target)
	try:
		req = urllib2.Request(url = target, data = post)
		req.add_header('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)')
		resp = urllib2.urlopen(req)
		http = resp.read()
		resp.close()
		#print http
		return http
	except Exception, e:
		print e

def login():
	username=__settings__.getSetting('kinozal_user')
	password=__settings__.getSetting('kinozal_pass')
	GET(httpSiteUrl+'/takelogin.php?', httpSiteUrl, 'username='+username+'&password='+password+'&returnto=')

def t2m(url):
	try:
		import bencode, hashlib
		#login()
		r = GET(url)
		metainfo = bencode.bdecode(r)
		announce=''
		if 'announce-list' in metainfo.keys():
			for ans in metainfo['announce-list']:
				announce=announce+'&tr='+urllib.quote_plus(ans[0])
		infohash = hashlib.sha1(bencode.bencode(metainfo['info'])).hexdigest()
		#announce=metainfo['info']['announce']
		#print announce
		magneturi  = 'magnet:?xt=urn:btih:'+str(infohash)+'&dn='+urllib.quote_plus(metainfo['info']['name'])+announce
		return magneturi
	except:
		return url

def get_magnet(id):
	announce_list = ['http://tr1.torrent4me.com/ann?uk=', 'http://tr0.tor4me.info/ann?uk=', 'http://tr0.tor2me.info/ann?uk=', 'http://tr1.tor4me.info/ann?uk=', 'http://tr1.tor2me.info/ann?uk=', 'http://tr2.tor4me.info/ann?uk=', 'http://tr2.tor2me.info/ann?uk=']
	hp=GET(httpSiteUrl+'/get_srv_details.php?id='+id+'&action=2')
	infohash = mfind(hp, ': ','</li>')
	name = mfind(hp, "class='b ing'>",'<')
	key=get_passkey()
	announce=''
	for ans in announce_list:
			announce=announce+'&tr='+urllib.quote_plus(ans+key)

	magneturi  = 'magnet:?xt=urn:btih:'+str(infohash)+'&dn='+urllib.quote_plus(name)+announce
	return magneturi

def get_passkey():
	try:passkey=__settings__.getSetting("passkey")
	except:passkey=''
	
	if passkey == '':
		login()
		hp=GET(httpSiteUrl+'/my.php')
		passkey=mfind(mfind(hp, '<span id="passk">','return up_passkey'), ': <b>','</')
		__settings__.setSetting("passkey", passkey)
		return passkey
	else: 
		return passkey

def get_list(url, info):
	title=info['title']
	print 'get_list: '+url
	login()
	hp=GET(url)
	#print hp
	hp=hp.replace('class="r1">', 'class="r0">')
	hp=hp.replace('class="r2">', 'class="r0">')
	L=mfindal(hp, 'class="bt"', "<td class='sl'>")
	#print L
	L2=[]
	update_Lt('reset')
	total_threads=len(L)
	
	for i in L:
		#itm=get_item(i, info)
		#if itm!={}: L2.append(itm)
		create_thread({'i':i, 'info':info})
	
	for t in range(10):
			if len(Lthread) == total_threads: break
			xbmc.sleep(500)
	
	for itm in Lthread:
			if itm!={}: L2.append(itm)
	
	return L2

def get_item(i, info):
		id = mfind(i,'details.php?id=','"')
		ttl= mfind(i,'class="r0">','<')
		ttl=rt(ttl.decode('windows-1251').encode('utf8'))
		tmp=i[i.find("<td class='s'>")+5:]
		size = mfind(tmp,"<td class='s'>",'<').replace('&nbsp;', '').strip()
		if '"right">' in size: size=size[size.find('"right">')+8:]
		if 'MB' in size: size=size[:size.find('.')]+'MB'
		seeds = mfind(i,"class='sl_s'>",'<').replace('&nbsp;', '').strip()
		
		print '----'
		#print id
		#print ttl
		#print size
		#print seeds
		
		if filtr(ttl, info):
			curl='http://dl.'+siteUrl+'/download.php?id='+id
			curl=get_magnet(id)
			itm ={"sids":seeds,"size":size, "title":xt(ttl),"url":curl}
			print 'A: '+ttl
		else:
			print 'F: '+ttl
			itm = {}
		return itm



#------------------------------------------------------
def update_Lt(d):
	global Lthread
	if d == 'reset':	Lthread=[]
	else:				Lthread.append(d)

from threading import Thread
class MyThread(Thread):
	def __init__(self, param):
		Thread.__init__(self)
		self.param = param
	
	def run(self):
		update_Lt(get_item(self.param['i'], self.param['info']))

def create_thread(param):
		my_thread = MyThread(param)
		my_thread.start()
#---------------------------------------------------


class Tracker:
	def __init__(self):
		pass

	def Search(self, info):
		t=urllib.quote_plus(xt(info['originaltitle']))
		
		url=httpSiteUrl+'/browse.php?s='+t+'&g=3&c=1001&v=0&d=0&t=1&f=0'
		Lout=get_list(url, info)
		
		return Lout