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

# *  Copyright (C) 2016 TDW

import xbmc, xbmcgui, xbmcplugin, xbmcaddon, os, urllib, urllib2, time, codecs, httplib

PLUGIN_NAME   = 'KinoPoisk-3.0'
siteUrl = 'www.KinoPoisk.ru'
httpSiteUrl = 'https://' + siteUrl
handle = int(sys.argv[1])
addon = xbmcaddon.Addon(id='plugin.video.KinoPoisk.ru')
__settings__ = xbmcaddon.Addon(id='plugin.video.KinoPoisk.ru')
xbmcplugin.setContent(int(sys.argv[1]), 'movies')

icon  = os.path.join( addon.getAddonInfo('path'), 'icon.png')
dbDir = __settings__.getSetting("DBDirectory")
if dbDir =='': dbDir = addon.getAddonInfo('path')
LstDir = addon.getAddonInfo('path')

import kinodb
kinodb.temp_dir=addon.getAddonInfo('path')


#======================== стандартные функции ==========================
def fs_enc_old(path):
	sys_enc = sys.getfilesystemencoding() if sys.getfilesystemencoding() else 'utf-8'
	return path.decode('utf-8').encode(sys_enc)

def fs_enc(path):
	path=xbmc.translatePath(path)
	sys_enc = sys.getfilesystemencoding() if sys.getfilesystemencoding() else 'utf-8'
	try:path2=path.decode('utf-8')
	except: pass
	try:path2=path2.encode(sys_enc)
	except: 
		try: path2=path2.encode(sys_enc)
		except: path2=path
	return path2


def fs_dec(path):
	sys_enc = sys.getfilesystemencoding() if sys.getfilesystemencoding() else 'utf-8'
	return path.decode(sys_enc).encode('utf-8')
def du(s):return eval('u"'+s.replace('\u','\\u')+'"')
def fs(s):
	#try: r = s.decode('windows-1251').encode('utf-8')
	#except: r=s
	return s
def win(s):return s.decode('utf-8').encode('windows-1251')
def ru(x):return unicode(x,'utf8', 'ignore')
def xt(x):return xbmc.translatePath(x)
def rt(x):#('&#39;','’'), ('&#145;','‘')
	L=[('&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:
		try:x=x.replace(i[0], i[1])
		except:pass
	return x

def lower_old(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 lower(t):
	RUS={"А":"а", "Б":"б", "В":"в", "Г":"г", "Д":"д", "Е":"е", "Ё":"ё", "Ж":"ж", "З":"з", "И":"и", "Й":"й", "К":"к", "Л":"л", "М":"м", "Н":"н", "О":"о", "П":"п", "Р":"р", "С":"с", "Т":"т", "У":"у", "Ф":"ф", "Х":"х", "Ц":"ц", "Ч":"ч", "Ш":"ш", "Щ":"щ", "Ъ":"ъ", "Ы":"ы", "Ь":"ь", "Э":"э", "Ю":"ю", "Я":"я"}
	for i in range (65,90):
		t=t.replace(chr(i),chr(i+32))
	for i in RUS.keys():
		t=t.replace(i,RUS[i])
	return t

def mid(s, n):
	try:s=s.decode('utf-8')
	except: pass
	try:s=s.decode('windows-1251')
	except: pass
	s=s.center(n)
	try:s=s.encode('utf-8')
	except: pass
	return s

def mids(s, n):
	l="                                              "
	s=l[:n-len(s)]+s+l[:n-len(s)]
	return s

def FC(s, color="FFFFFF00"):
	s="[COLOR "+color+"]"+s+"[/COLOR]"
	return s

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 debug(s):
	fl = open(ru(os.path.join( addon.getAddonInfo('path'),"test.txt")), "wb")
	fl.write(s)
	fl.close()

def deb_print(s):
	if __settings__.getSetting("DebMod")=='true': print s

def inputbox():
	skbd = xbmc.Keyboard()
	skbd.setHeading('Поиск:')
	skbd.doModal()
	if skbd.isConfirmed():
		SearchStr = skbd.getText()
		return SearchStr
	else:
		return ""

def showMessage(heading, message, times = 3000):
	xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s, "%s")'%(heading, message, times, icon))



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):
		i=self.param['i']
		try:
			exec ("import "+i[:-3]+"; skp="+i[:-3]+".Tracker()")
			L = skp.Search(self.param['info'])
		except: 
			L=[]
		
		update_Lt(L)

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


#====================== подготовка данных для интерфейса ================

from KPmenu import *

Category=[]
CategoryDict={}
for i in TypeList:
	Category.append(i[1])
	CategoryDict[i[1]]=i[0]

Genre=[]
GenreDict={}
for i in GenreList:
	Genre.append(i[1])
	GenreDict[i[1]]=i[0]

Cantry=[]
CantryDict={}
for i in CantryList:
	Cantry.append(i[1])
	CantryDict[i[1]]=i[0]

Year=[]
YearDict={}
for i in YearList:
	Year.append(i[1])
	YearDict[i[1]]=i[0]

Old=[]
OldDict={}
for i in OldList:
	Old.append(i[1])
	OldDict[i[1]]=i[0]

Sort=[]
SortDict={}
for i in SortList:
	Sort.append(i[1])
	SortDict[i[1]]=i[0]

Rating=[]
RatingDict={}
for i in RatingList:
	Rating.append(i[1])
	RatingDict[i[1]]=i[0]


#============================== основная часть ============================

def add_to_kinodb(info):
	try:
		kinodb.add(info)
	except:
		print 'ERR: add_to_kinodb'
		print info
		#import yadisk
		#yadisk.temp_dir=addon.getAddonInfo('path')
		#yadisk.add(info)

def update_kinodb(info):
	try:
		kinodb.update(info)
	except:
		print 'ERR: update_kinodb'
		print info


def get_trailer(id):
	try:
		url='https://www.kinopoisk.ru/film/'+id+'/video/type/1/'
		http=GET(url)
		ss='/share/'
		es='/?share'
		vod=mfind(http,ss,es)
		print vod
		
		#url2='https://widgets.kinopoisk.ru/discovery/film/'+id+'/trailer/'+vod+'?onlyPlayer=1'
		url2='https://widgets.kinopoisk.ru/discovery/trailer/'+vod+'?onlyPlayer=1'
		print url2
		http=GET(url2)
		#ss='"streamUrl":"'
		#es='"'
		#link=mfind(http,ss,es)
		#ss='"url":"'
		ss='"streamUrl":"'
		es='",'#"streamUrl
		url3=mfind(http,ss,es)
		print url3
		#return url3
		http=GET(url3)
		head = url3[:url3.rfind('/')+1]
		#ss='videoUrl&quot;:&quot;'
		#es='&quot;},&quot;webm'
		
		#ss='#EXT-X-MEDIA:URI="'
		#es='"'
		#link=mfind(http,ss,es)
		#tail = link[link.find('.m3u8')+5:]
		L=http.splitlines()
		for t in L:
			print t
			if '#EXT' not in t and 'redundant' not in t: link=t
		
		link=head+link.replace('&amp;','&')
		#link=url3+tail
		
		print link
		return link
	except: return ""

def get_rating(id, imdb_rating=''):
	try:
		url='https://rating.kinopoisk.ru/'+id+'.xml'
		http=GET(url).replace('rating>','rating>\n')
		L=http.splitlines()
		kp = 0
		imdb=0
		for i in L:
			if 'kp_rating'   in i: kp = float(i[i.find('">')+2:i.find('</kp')])
			if 'imdb_rating' in i: imdb=float(i[i.find('">')+2:i.find('</imdb')])
		if kp == 0 or imdb_rating!='': kp = imdb
		return kp
	except: return 0

def get_top_list():
	url='https://www.kinopoisk.ru/top/lists/'
	url='https://www.kinopoisk.ru/lists/films/1/'
	http=GET(url)
	n = http.find('film-lists__content')
	http=http[n:]
	L=mfindal(http,'<a href=','film-lists-item__films-count')
	L2=[]
	for i in L:
		if '/lists/' in i:
			i=i.replace('%22%20','" ').replace('%2f','/')
			id = mfind(i, '/lists/', '" ')
			title = mfind(i, 'film-lists-item__name">', '<')
			L2.append((id, title))
	return L2

def getList(id):
	try:L = eval(__settings__.getSetting(id))
	except:L =[]
	S=""
	for i in L:
		if i[:1]=="[": S=S+", "+i
	return S[1:]

def getList2(id):
	try:L = eval(__settings__.getSetting(id))
	except:L =[]
	S=[]
	for i in L:
		if i[:1]=="[": S.append(i.replace("[COLOR FFFFFF00]","").replace("[/COLOR]",""))
	return S


def setList(idw, L):
	__settings__.setSetting(id=idw, value=repr(L))

def POST(target, post=None, referer='http://torrentino.net'):
	#print 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)')
		#req.add_header('X-Requested-With', 'XMLHttpRequest')
		req.add_header('Content-Type', 'application/x-www-form-urlencoded')
		resp = urllib2.urlopen(req)
		print resp.info()
		http = resp.read()
		resp.close()
		return http
	except Exception, e:
		print e
		return ''

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 t2m(url):
	try:
		import bencode, hashlib
		r = GETtorr(url)
		metainfo = bencode.bdecode(r)
		infohash = hashlib.sha1(bencode.bencode(metainfo['info'])).hexdigest()
		magneturi  = 'magnet:?xt=urn:btih:'+str(infohash)+'&dn='+urllib.quote_plus(metainfo['info']['name'])
		return magneturi
	except:
		return url

def CRC32(buf):
		import binascii
		buf = (binascii.crc32(buf) & 0xFFFFFFFF)
		return str("%08X" % buf)

def play(url, ind=0, id='0'):
	le=['','ace', 't2http', 'yatp', 'torrenter', 'elementum', 'xbmctorrent', 'ace_proxy', 'quasar', 'torrserver']
	tengine = le[int(__settings__.getSetting("TAMengine"))]
	purl ="plugin://plugin.video.tam/?mode=play&url="+ urllib.quote_plus(url)+"&ind="+str(ind)+ '&engine='+tengine
	item = xbmcgui.ListItem(path=purl)
	xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)

def GET(url, Referer = 'http://www.KinoPoisk.ru/'):
	deb_print ('KP GET '+url)
	try:
		req = urllib2.Request(url)
		req.add_header('Referer', Referer)
		req.add_header('User-Agent', 'Opera/10.60 (X11; openSUSE 11.3/Linux i686; U; ru) Presto/2.6.30 Version/10.60')
		#req.add_header('User-Agent', 'TV+Android/1.1.5.2 (Linux;Android 7.1.1) ExoPlayerLib/2.9.1')
		req.add_header('Accept', '*/*')
		req.add_header('Accept-Language', 'ru,en;q=0.9')
		req.add_header('accept-encoding', 'gzip, deflate')
		#req.add_header('x-requested-with', 'XMLHttpRequest')
		
		response = urllib2.urlopen(req)
		if response.info().get('Content-Encoding') == 'gzip':
			from StringIO import StringIO
			import gzip
			buf = StringIO(response.read())
			f = gzip.GzipFile(fileobj=buf)
			data = f.read()
		else:
			data=response.read()
		response.close()
		return data
	except:
		return ''
		'''
		try:
			import requests
			s = requests.session()
			r=s.get(url).text
			rd=r.encode('windows-1251')
			return rd
		except:
			return '''

def GETjson(url,Referer = 'https://plus.kinopoisk.ru'):
		deb_print ('KP GETjson '+url)
		
		req = urllib2.Request(url)
		req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 OPR/46.0.2597.39')
		req.add_header('Accept', 'application/xml, application/xhtml+xml')
		req.add_header('Accept-Language', 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4')
		req.add_header('Referer', Referer)
		req.add_header('x-requested-with', 'XMLHttpRequest')
		response = urllib2.urlopen(req)
		link=response.read()
		response.close()
		return link

def GET2(url, Referer= 'https://plus.kinopoisk.ru'):
	try:
		import requests
		try:
			s = requests.session()
			r=s.get(url, timeout=(0.5, 3), verify=False).text#0.00001
		except:
			print 'requests: timeout'
			r=''
		#r=r.encode('windows-1251')
		return r
	except:
		return ''

def GETtorr(target):
	try:
			req = urllib2.Request(url = target)
			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)')
			#req.add_header('Accept', 'application/octet-stream')
			#req.add_header('Referer', 'http://hdpicture.ru')
			#req.add_header('Content-Transfer-Encoding', 'binary')
			resp = urllib2.urlopen(req)
			#resp = urllib2.urlopen(target)
			#debug (resp.read())
			return resp.read()
	except Exception, e:
			print 'HTTP ERROR ' + str(e)
			return None

def get_params():
	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




import sqlite3 as db
db_name = os.path.join( dbDir, "move_info.db" )
c = db.connect(database=db_name)
cu = c.cursor()
def add_to_db(n, item):
		deb_print ('KP add_to_db '+n)
		item=item.replace("'","XXCC").replace('"',"XXDD")
		err=0
		tor_id="n"+n
		litm=str(len(item))
		try:
			cu.execute("CREATE TABLE "+tor_id+" (db_item VARCHAR("+litm+"), i VARCHAR(1));")
			c.commit()
			deb_print ('KP add_to_db CREATE TABLE '+tor_id)
		except: 
			err=1
			print "Ошибка БД"+ n
			print item
		if err==0:
			cu.execute('INSERT INTO '+tor_id+' (db_item, i) VALUES ("'+item+'", "1");')
			c.commit()
			deb_print ('KP add_to_db INSERT INTO '+tor_id)
			#c.close()

def get_inf_db(n):
		deb_print ('KP get_inf_db '+n)
		tor_id="n"+n
		cu.execute(str('SELECT db_item FROM '+tor_id+';'))
		c.commit()
		deb_print ('KP get_inf_db SELECT '+tor_id)
		Linfo = cu.fetchall()
		info=Linfo[0][0].replace("XXCC","'").replace("XXDD",'"')
		deb_print ('KP get_inf_db return_info OK')
		return info

def rem_inf_db(n):
		deb_print ('KP rem_inf_db '+n)
		tor_id="n"+n
		try:
			cu.execute("DROP TABLE "+tor_id+";")
			c.commit()
			deb_print ('KP rem_inf_db DROP TABLE '+n)
		except: pass

def get_labels(info):
	Linf=['genre', 'year', 'rating', 'cast', 'director', 'plot', 'title', 'originaltitle', 'studio']
	Labels={}
	for inf in Linf:
		try:Labels[inf] = info[inf]
		except: pass
	try:Labels['duration'] = str(int(info['duration'])*60)
	except: pass
	return Labels


def AddItem(Title = "", mode = "", id='0', url='', total=100):
			if id !='0' and mode!="OpenTopList":
				if mode=="PersonFilm":
					cover='https://st.kp.yandex.net/images/actor_iphone/iphone360_'+id+".jpg"
					fanart = ''
					info={"cover":cover, "title":Title, "id":id}
				else:
					try:
						if mode=="OpenTorrent":
							info = {}
							try: l_id=__settings__.getSetting("l_id")
							except: l_id='0'
							if l_id == id:
								try: info = eval(__settings__.getSetting("l_inf"))
								except: info = {}
							
							if info=={}: 
								info=get_info(id)
								__settings__.setSetting("l_id", id)
								__settings__.setSetting("l_inf", repr(info))
						else:
							info=get_info(id)
					except: info={}
					
					try:    cover = info["cover"]
					except: cover = icon
					try:    fanart = info["fanart"]
					except: fanart = ''
			else:
				cover = icon
				fanart = ''
				info={'id':id}
			
			if mode=="OpenTorrent":
				if 'magnet:' in url: cover = os.path.join( addon.getAddonInfo('path'), 'U.png')
				else:				 cover = os.path.join( addon.getAddonInfo('path'), 'T.png')

			listitem = xbmcgui.ListItem(Title, iconImage=cover, thumbnailImage=cover)
			listitem.setInfo(type = "Video", infoLabels = get_labels(info))
			try: listitem.setArt({ 'poster': cover, 'fanart' : fanart, 'thumb': cover, 'icon': cover})
			except: pass
			listitem.setProperty('fanart_image', fanart)
			
			purl = sys.argv[0] + '?mode='+mode+'&id='+id
			if url !="": purl = purl +'&url='+urllib.quote_plus(url)
			print purl
			if mode=="Torrents":
				listitem.addContextMenuItems([('[B]Hайти похожие[/B]', 'Container.Update("plugin://plugin.video.KinoPoisk.ru/?mode=Recomend&id='+id+'")'), ('[B]Персоны[/B]', 'Container.Update("plugin://plugin.video.KinoPoisk.ru/?mode=Person&id='+id+'")'), ('[B]Трейлер[/B]', 'Container.Update("plugin://plugin.video.KinoPoisk.ru/?mode=PlayTrailer&id='+id+'")'), ('[B]Рецензии[/B]', 'Container.Update("plugin://plugin.video.KinoPoisk.ru/?mode=Review&id='+id+'")'), ('[B]Буду смотреть[/B]', 'Container.Update("plugin://plugin.video.KinoPoisk.ru/?mode=Add2List&id='+id+'")'), ('[B]Список раздач[/B]', 'Container.Update("plugin://plugin.video.KinoPoisk.ru/?mode=Torrents2&id='+id+'")'), ('[B]Обновить описание[/B]', 'Container.Update("plugin://plugin.video.KinoPoisk.ru/?mode=update_info&id='+id+'")')])
			if mode=="PlayTorrent" or mode=="PlayTorrent2":
				listitem.addContextMenuItems([('[B]Сохранить фильм(STRM)[/B]', 'Container.Update("plugin://plugin.video.KinoPoisk.ru/?mode=save_strm&id='+id+'&url='+urllib.quote_plus(url)+'")'),])
			if mode=="OpenTorrent":
#				if __settings__.getSetting("Engine")=="7": 
				le=['','ace', 't2http', 'yatp', 'torrenter', 'elementum', 'xbmctorrent', 'ace_proxy', 'quasar', 'torrserver']
				tengine = le[int(__settings__.getSetting("TAMengine"))]
				
				pu='plugin://plugin.video.KinoPoisk.ru/?mode=Torrents&id='+id
				purl='plugin://plugin.video.tam/?mode=open&url='+urllib.quote_plus(url)+ '&info='+urllib.quote_plus(repr(info))+ '&purl='+urllib.quote_plus(pu)+ '&engine='+tengine
				
				try:type=info["type"]
				except:type=''
				
				if type != '': listitem.addContextMenuItems([('[B]Сохранить сериал[/B]', 'Container.Update("plugin://plugin.video.tam/?mode=save_series&url='+urllib.quote_plus(url)+'&purl='+urllib.quote_plus(pu)+'&name='+urllib.quote_plus(info['originaltitle'])+ '&info=' + urllib.quote_plus(repr(info))+'")'),])
				else: listitem.addContextMenuItems([('[B]Сохранить фильм(STRM)[/B]', 'Container.Update("plugin://plugin.video.tam/?mode=save_movie&purl='+urllib.quote_plus(pu)+'&url='+urllib.quote_plus(url)+ '&info=' + urllib.quote_plus(repr(info))+'")'),])
				
			if mode=="PersonFilm":
				listitem.addContextMenuItems([('[B]Добавить в Персоны[/B]', 'Container.Update("plugin://plugin.video.KinoPoisk.ru/?mode=AddPerson&info='+urllib.quote_plus(repr(info))+'")'), ('[B]Удалить из Персоны[/B]', 'Container.Update("plugin://plugin.video.KinoPoisk.ru/?mode=RemovePerson&info='+urllib.quote_plus(repr(info))+'")')])
			if mode=="Wish":
				listitem.addContextMenuItems([('[B]Удалить задание[/B]', 'Container.Update("plugin://plugin.video.KinoPoisk.ru/?mode=RemItem&&id='+id+'")'),])
			
			try:type=info["type"]
			except:type=''
			if __settings__.getSetting("Autoplay") == 'true' and mode=="Torrents" and type=="":
				listitem.setProperty('IsPlayable', 'true')
				purl = sys.argv[0] + '?mode=Autoplay&id='+id
				xbmcplugin.addDirectoryItem(handle, purl, listitem, False, total)
			else:
				xbmcplugin.addDirectoryItem(handle, purl, listitem, True, total)

def AddPerson(info):
		try:PL=eval(__settings__.getSetting("PersonLst"))
		except: PL=[]
		if info not in PL: 
			PL.append(info)
			__settings__.setSetting(id="PersonLst", value=repr(PL))

def RemovePerson(info):
		try:PL=eval(__settings__.getSetting("PersonLst"))
		except: PL=[]
		NL=[]
		for i in PL:
				if i!=info: NL.append(i)
		__settings__.setSetting(id="PersonLst", value=repr(NL))

def PersonList():
		try:PL=eval(__settings__.getSetting("PersonLst"))
		except: PL=[]
		for i in PL:
			id = i['id']
			AddItem(i["title"], "PersonFilm", id, '',len(PL))

def PersonPopular():
	link='https://www.kinopoisk.ru/popular/names/'
	http = GET (link, 'https://www.kinopoisk.ru/')
	L=http.splitlines()
	for i in L:
		if 'style="font:100 12px arial,sans-serif">' in i:
			#print i
			id=mfind(i, '/name/', '/" style').replace('/name/','')
			nm=fs(mfind(i, '">', '</a>')).replace('">','')
			#print id+' '+nm
			if len(nm)>0 and len(id)>0 :AddItem(xt(nm), "PersonFilm", id,'', 200)

def Person():
	try:id = urllib.unquote_plus(get_params()["id"])
	except: id = ''
	link="https://www.kinopoisk.ru/film/"+id+"/cast/"
	ss='<div style="padding-left:'
	se='<a name="'
	http = GET (link, httpSiteUrl)
	http=http[http.find('<div style="padding-left:'):]
	L=mfindal(http, ss, se)
	
	for i in L:
		ss='font-size: 16px">'
		se='</div>'
		tb=mfindal(i, ss, se)[0][17:]
		AddItem(FC(fs(tb)), "", '0', '', len(L))
		
		ss='title="/images/sm_actor/'
		se='" /></a></div>'
		L2=mfindal(i, ss, se)
		for j in L2:
			#print j
			n=j.find('" alt="')
			nm=j[n+7:]
			id=j[24:n-4]
			#print '--'
			#print xt(nm)
			#cover="http://st.kp.yandex.net/images/sm_actor/"+id+".jpg"
			cover="http://st.kp.yandex.net/images/actor_iphone/iphone360_"+id+".jpg"
			#.replace('sm_film/','film_iphone/iphone360_')+'.jpg'
			#info={"cover":cover, "title":nm, "id":id}
			#print info
			if id!='':AddItem(fs(nm), "PersonFilm", id, '', len(L))

def Person2():
	try:ID = urllib.unquote_plus(get_params()["id"])
	except: return
	print ID
	url='http://getmovie.cc/api/kinopoisk.json?token=daf8253b05fc622bda935ba9042bbe5a&id='+ID
	print url
	json=eval(GET(url).replace('null','""').replace('\\/','/'))#.replace('\u','\\u')
	print json
	try:L=json["creators"]["actor"]
	except:L=[]
	for actor in L:
			actor_name=actor['name_person_ru']
			print actor_name
			id=actor['kp_id_person']
			#actor_photo=actor['photos_person']
			AddItem(fs(actor_name), "PersonFilm", id, '', len(L))

def SrcNavi(md="Navigator", curl=''):
	if __settings__.getSetting('ShowProgress') == 'true':
		progressBar = xbmcgui.DialogProgressBG()
		progressBar.create('Кинопоиск', 'Загрузка списка')
	src=True
	#ss="/level/1/film/"
	ss='id="film_eye_'
	#se='/">'
	se='"></div>'

	if md =="Navigator":
		Cats=getList("CutList")
		#Genres=getList("GenreList")
		Cantrys=getList("CantryList")
		Years=__settings__.getSetting("YearList")
		Old=__settings__.getSetting("OldList")
		Sort=__settings__.getSetting("SortList")
		Rating=__settings__.getSetting("RatingList")

		Cat=getList2("CatList")
		sCat=""
		for i in Cat:
			sCat=sCat+"m_act%5B"+str(CategoryDict[i])+"%5D/on/"
		if sCat == "m_act%5B%5D/on/" or sCat == "m_act%5Ball%5D/on/": sCat =""
	
		Cantry=getList2("CantryList")
		Cantrys=""
		for i in Cantry:
			Cantrys=Cantrys+","+str(CantryDict[i])
		Cantrys=Cantrys[1:]
		if Cantrys == "" or Cantrys == "0": sCantry =""
		else: sCantry = "m_act%5Bcountry%5D/"+ Cantrys+"/"

		Genre=getList2("GenreList")
		Genres=""
		for i in Genre:
			Genres=Genres+","+str(GenreDict[i])
		Genres=Genres[1:]
		if Genres == "" or Genres == "0": sGenre =""
		else: sGenre = "m_act%5Bgenre%5D/"+ Genres+"/"

		try:YearId = YearDict[Years]
		except:YearId="0"
		if YearId == "0": sYear = ""
		else: sYear = "m_act%5Bdecade%5D/"+ YearId+"/"
	
		try:OldId = OldDict[Old]
		except:OldId=""
		if OldId == "": sOld = ""
		else: sOld = "m_act%5Brestriction%5D/"+ OldId+"/"
	
		try:RatingId = RatingDict[Rating]
		except:RatingId=""
		if RatingId == "": sRating = ""
		else: sRating = "m_act%5Brating%5D/"+ RatingId+":/"
	
		try:sSort = SortDict[Sort]
		except:sSort = "order/rating"
		
		if sCat.find("is_serial%5D/on")<0 and sCat!="": sGenre=sGenre+"m_act%5Begenre%5D/999/"
		#print sCat
		#print sGenre
		link=httpSiteUrl+"/top/navigator/"+sGenre+sCantry+sYear+sRating+sOld+sCat+sSort+"/perpage/100/#results"
		
		if link=="http://www.KinoPoisk.ru/top/navigator/order/rating/perpage/100/#results": 
			link="http://www.KinoPoisk.ru/top/navigator/m_act%5Brating%5D/7:/order/rating/perpage/100/#results"
			
	elif md=='Extend':#Navigator
		ss='data-id="'
		se='" data-type'
		
		Type=__settings__.getSetting("Type")
		Genres=getList("GenreList")
		Cantrys=getList("CantryList")
		Year=__settings__.getSetting("Year")
		
		sType = "m_act[type]/"+Type+"/"
	
		Cantry=getList2("CantryList")
		Cantrys=""
		for i in Cantry:
			Cantrys=Cantrys+","+str(CantryDict[i])
		Cantrys=Cantrys[1:]
		if Cantrys == "" or Cantrys == "0": sCantry =""
		else: sCantry = "m_act[country]/"+ Cantrys+"/"

		Genre=getList2("GenreList")
		Genres=""
		for i in Genre:
			Genres=Genres+","+str(GenreDict[i])
		Genres=Genres[1:]
		if Genres == "" or Genres == "0": sGenre =""
		else: sGenre = "m_act[genre][0]/"+ Genres+"/"
		
		if Year == "" or Year == "--": sYear = ""
		else: sYear = "m_act[year]/"+ Year+"/"
		
		#try:sSort = SortDict[Sort]
		#except:sSort = "order/rating"
		
		link='https://www.kinopoisk.ru/s/type/film/list/1/'+sGenre+sYear+sCantry+sType+'perpage/200/'#m_act[genre][0]/3/m_act[year]/1995/m_act[country]/1/m_act[type]/serial/page/1/
		print link
		
	elif md=="Popular": link="http://www.kinopoisk.ru/top/lists/186/filtr/all/sort/order/perpage/200/"
	elif md=="New": link="http://www.kinopoisk.ru/top/lists/222/perpage/100/"
	elif md=="New2": link="http://www.kinopoisk.ru/top/navigator/m_act%5Bis_film%5D/on/m_act%5Bis_mult%5D/on/order/premiere/#results"
	elif md=="Future": 
		#link="http://www.kinopoisk.ru/top/lists/220/"
		link="http://www.kinopoisk.ru/comingsoon/sex/all/sort/date/period/halfyear/"
		ss='id="top_film_'
		se='" class="item" style="z'
	elif md=="Recomend": 
		try:id = urllib.unquote_plus(get_params()["id"])
		except: id = ''
		link="http://www.kinopoisk.ru/film/"+id+"/like/"
		#print link
	elif md=="PersonFilm":
		id = get_params()["id"]
		#try:id = eval(urllib.unquote_plus(get_params()["info"]))["id"]
		#except: id = ''
		link="https://www.kinopoisk.ru/name/"+id+"/"
		ss=".folder_film_"
		se='").folder'
		print link
	elif md=="OpenTopList":
		id = get_params()["id"].replace('%2f','/')
		#link="https://www.kinopoisk.ru/top/lists/"+id+"/perpage/200/"
		link="https://www.kinopoisk.ru/lists/"+id
		print link
		ss='<a href="/film/'
		se='/" class="selection-film-item-meta__link'
	elif md=="NewReleases":
		link="https://www.kinopoisk.ru/top/lists/322/filtr/all/sort/year/perpage/200/"
		ss='<tr id="tr_'
		se='" class='
		
	elif md=="Next":
		link=curl
		if '/s/type/' in curl:
				ss='data-id="'
				se='" data-type'
		if 'ru/lists/' in curl:
			ss='<a href="/film/'
			se='/" class="selection-film-item-meta__link'
			
	else: 
		link='http://www.kinopoisk.ru/index.php?first=no&what=&kp_query='+urllib.quote(win(md))
		link='https://www.kinopoisk.ru/s/type/film/list/1/find/'+urllib.quote(win(md))+'/order/relevant/perpage/10/'
		print link
		ss='data-id="'
		se='" data-type='
		src=False
	
	#=-=-=-=-=-=- get request =-=-=-=-=-
	if __settings__.getSetting("YaMod")=='true':
		try:
			#import yadisk
			#yadisk.temp_dir=addon.getAddonInfo('path')
			Dy=kinodb.get_request(link)
			Ly=Dy['list']
			Ty=int(Dy['update'])
		except:
			Ly=[]
			Ty=0
	else:
			Ly=[]
			Ty=0
	#=-=-=-=-=-=- get request =-=-=-=-=-
	
	
	
	Lid=[]
	if Ly==[] or time.time()-Ty > 86400:
	#print link
		http = GET (link, httpSiteUrl)
		if '<p class="show_all">' in http: http=http[:http.find('<p class="show_all">')]
		
		if md=="PersonFilm":
			c1=http.find('class="specializationBox first_pers_block">')
			c2=http.find('class="specializationBox">')
			if c2>c1: http=http[c1:c2]
		#debug (http)
		L=mfindal(http, ss, se)
		L2=[]
		
		for i in L:
			id = i[len(ss):]
			if id not in L2 and i<>"": L2.append(id)
	
		#=-=-=-=-=-=- save request =-=-=-=-=-
		if L2!=[] and __settings__.getSetting("YaMod")=='true':
			try:
				#import yadisk
				#yadisk.temp_dir=addon.getAddonInfo('path')
				kinodb.save_request(link, {'list':L2, 'update': time.time()})
			except: pass
		#=-=-=-=-=-=- save request =-=-=-=-=-
		
		if Ly!=[] and L2==[]: L2=Ly
		
	else:
		L2=Ly
	ci=0
	for id in L2:#[:-1]
		ci+=1
		prz=int((ci*100/len(L2)))
		#id = i[len(ss):]
		
		try:
			try:
				if __settings__.getSetting("FastMod")=='true' and src:  info = get_info_fast(id)
				else: 													info = get_info(id)
			except:
				info={"title": id, "originaltitle":id, "rating":0, "cover":icon, "type":'', "id":id}
			
			rating_kp = info['rating']
			#if __settings__.getSetting('TrueRat')=='true': rating_kp = get_rating(id)
			if rating_kp>0: rkp = str(rating_kp)[:3]
			else: rkp= " - - "
			nru = info['title']
			
			if info['type'] !="": type = " [COLOR 55FFFFFF]("+info['type']+")[/COLOR]"
			else: type = ''
			
			if md=="Future":
				try:
					rkp=info['premiered'][:-5]
					if rkp[1]=='.':rkp="0"+rkp
					if rkp=='': rkp= " __.__ "
				except: rkp= " __.__ "
			
			try: 
				if info['type']!= "fast": AddItem("[ "+rkp+" ] "+nru+type, "Torrents", id, total=len(L2)-2)
				else: Lid.append(id)
			except: pass
			try:progressBar.update(prz, 'Кинопоиск', nru+type)
			except: pass
		except: 
			print 'ошибка получения описания'
			pass
	
	try:progressBar.close()
	except: pass
	
	if md=="Extend" or md=="Popular" or md =="Navigator" or (md == 'OpenTopList' and len(L2)>29) or (md == 'Next' and len(L2)>29):
		next = get_next(link)
		print next
		AddItem("[ Далее > ]", "Next", '0', next)
	
	
	if Lid!=[] and src:
		if len(Lid)>10:
			xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
			xbmcplugin.endOfDirectory(handle)
		try:
			pDialog = xbmcgui.DialogProgressBG()
			pDialog.create('Кинопоиск', 'Загрузка описаний ...')
			pDialog.update(0, message='Загрузка описаний ...')
		except: pass
		n=0
		for id in Lid:
			n+=1
			try:pDialog.update(n*100/len(Lid), message='Загрузка описаний ...')
			except: pass
			info = get_info(id)
			if n==10 or n==len(Lid): 
				try: pDialog.close()
				except: pass
				if len(Lid)>10: xbmc.executebuiltin('Container.Refresh')
				return
				
		try: pDialog.close()
		except: pass
		#xbmc.executebuiltin('Container.Refresh')
		

def get_next(url):
	if 'ru/lists/' in url:
		url=url.replace('%2f','/')
		if '?page=' not in url:
			link=url+'/?page=2'
			link=link.replace('//?','/?')
			return link
		else:
			p1 = url[url.find('?page=')+6:]
			p2 = str(int(p1)+1)
			link = url.replace('?page='+p1,'?page='+p2)
			return link
	else:
		if '#results' in url: 
			url=url.replace('#results','')
			results='#results'
		else:
			results=''
		
		if '/page/' in url: 
			p1 ='/page/'+mfind(url,'/page/','/')+'/'
			p2 = '/page/'+str(int(mfind(url,'/page/','/'))+1)+'/'
			link = url.replace(p1,'')+p2
		else:
			link = url+'/page/2/'
		
		return link+results

def load():
	s=inputbox()
	p=int(s)
	
	for i in range(0,100):
		if i<10: si='0'+str(i)
		else: si=str(i)
		id = s+si
		try:info = get_info(id)
		except:info={"title": id, "originaltitle":id, "rating":0, "cover":icon, "type":'', "id":id}
		
		nru = info['title']
		
		if info['type'] !="": type = " ("+info['type']+")"
		else: type = ''
		
		AddItem("[ "+id+" ] "+nru+type, "Torrents", id, total=99)
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)


def update_info(id, up=True):
	try:
		rem_inf_db(id)
		info = get_info_kinodb(id, True)
		add_to_db(id, repr(info))
		if up: xbmc.executebuiltin('Container.Refresh')
	except:
		pass

def get_info_fast(ID):
	try:
			info=eval(xt(get_inf_db(ID)))
			deb_print ('KP get_info ОК')
			return info
	except:
			return {"title": ID, "originaltitle":ID, "rating":0, "cover":icon, "type":'fast', "id":ID}

def get_info_hd(ID, r=''):
	print '###### get_info_hd #####'
	if r=='':
		url='https://www.kinopoisk.ru/film/'+ID
		print url
		r=fs(GET(url))
		#debug (r)
	
	if '<meta property="og:description" content="' in r: 
		rus = mfind(r, '<meta property="og:description" content="', '(').strip()
		tmp = mfind(r, '<meta property="og:description" content="', '/>')
		eng = mfind(tmp, ') – ', ' – ').strip()
		year= mfind(tmp, '(', ')').strip()
	else: 
		rus=mfind(r, 'itemprop="name">', '<').replace('<span>','').replace('\t','').replace('\n','').strip()
		eng=rus
	
	print rus
	print eng
	#print year
	
	plot = mfind(r,'<p class="film-synopsis__paragraph">','<')
	print plot
	
	if '>О сериале<' in r: 	type='сериал'
	else: 						type=''
	
	if '>Жанр<' in r:
		tmp = mfind(r, '>Жанр<', '</a>')+'<'
		genre = mfind(tmp, 'serials">', '<')
	else: genre = ''
	cover = 'https://st.kp.yandex.net/images/film_iphone/iphone360_'+ID+'.jpg'
	fanart= 'https:'+mfind(r, 'srcSet="', ' 1x')
	
	rating_kp = get_rating(ID)
	
	info = {"title": rt(rus),
		"originaltitle":rt(eng),
		"year":year, 
		"genre":rt(genre),
		"rating":rating_kp,
		"cover":cover,
		"fanart":fanart,
		"plot":rt(plot),
		"type":type,
		"id":ID
		}
	
	#if 'captcha' not in rus and rus!='': add_to_kinodb(info)
	return info

def get_info_json(ID,r=''):
	print '###### get_info_json #####'
	if r=='':
		url='https://www.kinopoisk.ru/film/'+ID
		print url
		r=fs(GET(url))
		#debug (r)
	sjsn = mfind(r, '<script id="__NEXT_DATA__" type="application/json">', '</script>')
	sjsn = sjsn.replace('$Film:'+ID+'.','').replace('Film:'+ID+'.','').replace(':'+ID+'"','"')#.replace('','').replace('','').replace('','').replace('','').replace('','').replace('','').replace('','').replace('','').replace('','').replace('','').replace('','')
	null = None
	false = False
	true = True
	json = eval(sjsn)
	#debug (sjsn)
	''''
	for i in json['props']['apolloState']['data'].keys():#initialState
		print '- '+i+' > '+repr(json['props']['apolloState']['data'][i])
		try:
			for j in json[i].keys():
				print '-- '+j+' '+repr(json[i][j])
		except:
				pass
		'''
	data = json['props']['apolloState']['data']
	eng = data ['title']['original']
	try: rus = data ['title']['russian']
	except: rus = eng
	try:rating_kp = float(data ['rating.kinopoisk']['value'])
	except:rating_kp = 0
	try:genre = data ['genres.0']['name']
	except: genre = ''
	try:plot = data ['Film']['synopsis']
	except: plot = ''
	try: year = data ['Film']['productionYear']
	except: year = ''
	
	try:
		id_d = data ['members({"limit":4,"role":"DIRECTOR"}).items.0']['person']['id']
		director = data [id_d]['name']
	except: director = ''
	
	cast = []
	try:
		id_a0 = data ['members({"limit":10,"role":["ACTOR","CAMEO","UNCREDITED"]}).items.0']['person']['id']
		actor0 = data [id_a0]['name']
		cast.append(actor0)
		id_a1 = data ['members({"limit":10,"role":["ACTOR","CAMEO","UNCREDITED"]}).items.1']['person']['id']
		actor1 = data [id_a1]['name']
		cast.append(actor1)
		id_a2 = data ['members({"limit":10,"role":["ACTOR","CAMEO","UNCREDITED"]}).items.2']['person']['id']
		actor2 = data [id_a2]['name']
		cast.append(actor2)
	except: pass
	
	if rating_kp == 0: rating_kp = get_rating(ID)
	
	if '>О сериале<' in r: 	type='сериал'
	else: 						type=''
	
	cover = 'https://st.kp.yandex.net/images/film_iphone/iphone360_'+ID+'.jpg'
	if 'Трейлер" src="' in r: fanart= 'https:'+mfind(r, 'Трейлер" src="', '"')
	else: fanart= 'https:'+mfind(r, 'srcSet="', ' 1x')
	
	info = {"title": rt(rus),
		"originaltitle":rt(eng),
		"year":year, 
		"genre":rt(genre),
		"rating":rating_kp,
		"cover":cover,
		"fanart":fanart,
		"plot":rt(plot),
		"type":type,
		"director":rt(director),
		"cast":cast,
		"id":ID
		}
	
	if 'captcha' not in r and rus!='': add_to_kinodb(info)
	return info


#print get_info_json('994646')

def get_info_plus(ID):
	print '===========get_info_plus=============='
	url='https://www.kinopoisk.ru/film/'+ID
	r=fs(GET(url))
	#debug (r)
	if '<script id="__NEXT_DATA__" type="application/json">' in r: return get_info_json(ID, r)
	if 'moviename-big" itemprop="name">' not in r: return get_info_hd(ID, r)
	
	
	if 'captcha' in r: raise Exception("captcha")
	
	r=r.replace('<span class="moviename-title-wrapper">','')
	#print r
	
	
	
	if ">режиссер<" in r:
		dirpart = r[r.find(">режиссер<"):]
		director=mfind(dirpart,'/">',"<")
	else: director=""
	
	cast=[]
	if '<h4>В главных ролях:</h4>' in r:
		castpart = mfind(r,'<h4>В главных ролях:</h4>','</li></ul>')
		
		Lcast=mfindal(castpart,'/">','</a></li>')
		n=0
		for c in Lcast:
			n+=1
			if n<8 and len(c)<100:
				cast.append(xt(c).replace('/">',""))
	
	try:
		if 'dates/" title="">' in r:
			premiered=mfind(r, 'dates/" title="">', "<")
			premiered=mont2num(premiered)
			if premiered[1]==".": premiered="0"+premiered
		else: premiered=''
	except: premiered=''
	
	rus=mfind(r, 'moviename-big" itemprop="name">', '<').replace('\t','').replace('\n','').strip()
	
	try:
		if 'alternativeHeadline">' in r: eng=mfind(r, 'alternativeHeadline">', '<')
		else: eng=rus
	except: eng=rus
	if eng=='null' or eng=='': eng=rus
	
	try:
		if '<td class="type">год</td>' in r: year=mfind(mfind(r, '<td class="type">год</td>', '</div></td>'), 'title="">', '<')
		else: year=""
	except:year=""
	
	try:
		if '<span style="color: #999">/</span>' in r: duration=mfind(r, '<span style="color: #999">/</span>', '<')
		else: duration=mfind(r, 'class="time" id="runtime">', '<')
	except:duration='0:00'
	if len(duration)>10: duration='0:00'
	
	try:
		if '<span itemprop="genre">' in r: genre=mfind(mfind(r, '<span itemprop="genre">', '</span>'), '">', '</a>')
		else: genre=''
	except:genre=''
	
	try:
		if '<td class="type">страна</td>' in r: production=mfind(mfind(r, '<td class="type">страна</td>', '</div></td>'), '/">', '<')
		else: production=''
	except:production=''
	
	try:rating_kp=float(mfind(r, 'ratingValue" content="', '"'))
	except:rating_kp=0
	
	if rating_kp == 0: 
		try:rating_kp=float(mfind(r, 'IMDb: ', ' ('))
		except:rating_kp=0
		#rating_kp = get_rating(id, 'imdb')
	
	if 'og:type" content="video.' in i:
		try:type=mfind(r,'og:type" content="video.','" />')
		except:type=''
		if len(type)>20:type=''
		if type=='movie':type=''
		if type=='tv_show':type='сериал'
	else:
		if 'о сериале:' in r: type='сериал'
		else: type=''
	
	try:
		if 'share_description' in r: plot=mfind(r,'share_description" content="','" />')
		else: plot=""
	except:plot=""
	
	try:
		if 'videothumbnail" href="' in r: fanart=mfind(r,'videothumbnail" href="','" />')
		else: fanart=""
	except:fanart=""
	
	cover = 'https://st.kp.yandex.net/images/film_iphone/iphone360_'+ID+'.jpg'
	
	info = {"title": rt(rus),
		"originaltitle":rt(eng),
		"year":year, 
		"duration":duration,
		"genre":rt(genre),
		"studio":rt(production),
		"director":rt(director),
		"cast":cast,
		"rating":rating_kp,
		"cover":cover,
		"fanart":fanart,
		"plot":rt(plot),
		"type":type,
		"premiered":premiered,
		"id":ID
		}
	
	if 'captcha' not in rus and rus!='': add_to_kinodb(info)
	if __settings__.getSetting("WaitMod")=='true': xbmc.sleep(100)

	print '===========get_info=====ОК========='
	return info

#get_info_plus('899860')

def get_info_getmoviecc(ID):
		#try:
			deb_print ('=== get_info_getmoviecc ===')
			url='http://apiget.ru/?kinopoisk_id='+ID+'&key=bae5af3849042a79976126bb6f43a9d1'
			deb_print (url)
			req=GET2(url).replace('null','"null"')
			deb_print (req)
			json=eval(req)#.replace('\\/','/')#.replace('""','/'))#.replace('\u','\\u')
			
			try:rating_kp = get_rating(ID)
			except:rating_kp=0
			
			
			role=json['main_role']
			cast=[]
			for r in role.keys():
				cast.append(xt(role[r]))
			if json['type'] == 'movie': type=''
			elif json['type'] == 'serial': type='сериал'
			else: type=json['type']
			#cast=role.splitlines()
			info = {"title": xt(json['title_ru']),
					"originaltitle": json['title_en'],
					"year": json['year'], 
					"duration": json['duration'],
					"genre": xt(json['genre']),
					"studio": xt(json['country']),
					"director": xt(json['director']),
					"cast": cast,
					"rating": rating_kp,
					"cover": json['poster_film_small'],
					"fanart": json['preview'],
					"plot": xt(json['description']),
					"type": type,
					"id": ID
					}
			if json['title_en']!='null': add_to_kinodb(info)
			deb_print (info)
			return info
		#except:
		#	return {"title": ID, "originaltitle":ID, "rating":0, "cover":icon, "type":'', "id":ID}


def get_info(ID):
	try:
			upd=False
			info=eval(xt(get_inf_db(ID)))
			if 'captcha' in info['title']: 		upd=True
			if info['title']=='': 				upd=True
			if '\n' in info['title']: 			upd=True
			if 'блокування' in info['title']: 	upd=True
			
			if upd:
				update_info(ID, False)
				info = get_info_kinodb(ID)
				
			deb_print ('KP get_info ОК')
			return info
	except:
		if __settings__.getSetting("LocalMod2")=='3':
				deb_print ('info mod 3')
				return {"title": ID, "originaltitle":ID, "rating":0, "cover":icon, "type":'', "id":ID}
		
		elif __settings__.getSetting("LocalMod2")=='2': 
				deb_print ('info mod 2')
				try: 
					inf=get_info_kinodb(ID)
					info=inf
					#inf['title']='[COLOR FFFF5555]'+inf['title']+'[/COLOR]'
					#return inf
				except: 
					return {"title": ID, "originaltitle":ID, "rating":0, "cover":icon, "type":'', "id":ID}
		
		
		elif __settings__.getSetting("LocalMod2")=='1':
			deb_print ('info mod 1')
			try:    info = get_info_kinodb(ID)
			except: 
				try:info = get_info_plus(ID)
				except:
					try:info = get_info_getmoviecc(ID)
					except: info = {"title": 'null', "originaltitle":'null', "rating":0, "cover":icon, "type":'', "id":ID}
		
		else:
			deb_print ('info mod 0')
			try:    info = get_info_plus(ID)
			except: 
				try:info = get_info_kinodb(ID)
				except:
					try:info = get_info_getmoviecc(ID)
					except: info = {"title": 'null', "originaltitle":'null', "rating":0, "cover":icon, "type":'', "id":ID}
		
		if info['title']=='null' and info['originaltitle']=='null': return {"title": ID, "originaltitle":ID, "rating":0, "cover":icon, "type":'', "id":ID}
		
		try:
				add_to_db(ID, repr(info))
				#print "ADD: " + FilmID
		except:
				print "ERR: " + ID
				#print repr(info)
		deb_print ('KP return info')
		return info


def get_new_info(ID):
		try: info = get_info_plus(ID)
		except: info = {"title": 'null', "originaltitle":ID, "rating":0, "cover":icon, "type":'', "id":ID}
		#if info["title"]=='': info = get_info_getmoviecc(ID)
		#add_to_db(ID, repr(info))
		return info


def get_info_kinodb(id, upd=False):
	new=False
	info=kinodb.get_info(id)
	if 'captcha' in info['title']: upd=True
	if 'XHTML'  in info['plot']:   upd=True
	if info['title'] == ''       : upd=True
	if 'блокування' in info['title']: upd=True
	if len(info['type'])>20: upd=True
	
	if upd: info=get_new_info(id)
	#else:   info=kinodb.get_info(id)
	
	rating = info['rating']
	if rating == 0 or upd:
		rating = get_rating(id)
		if rating != 0: 
			info['rating']= rating
			new=True
	
	if info['title'] == 'null': 
		info['title']=info['originaltitle']
		new=True
	
	if len(info['director']) > 300: 
		info['director']=""
		new=True
		
	if new or upd and info['title'] != id: update_kinodb(info)
	return info


def mont2num(dt):
	L1=[' января ',' февраля ',' марта ',' апреля ',' мая ',' июня ',' июля ',' августа ',' сентября ',' октября ',' ноября ',' декабря ']
	L2=['.01.','.02.','.03.','.04.','.05.','.06.','.07.','.08.','.09.','.10.','.11.','.12.']
	for i in range (0,12):
		dt=dt.replace(L1[i], L2[i])
	return dt

#==============  Menu  ====================
def Root():
	try:L=eval(__settings__.getSetting("W_list"))
	except: L=[]
	AddItem("Поиск", "Search")
	if __settings__.getSetting("HistoryON") ==   'true': AddItem("История", "History")
	if __settings__.getSetting("NavigatorON") == 'true': AddItem("Навигатор", "Navigator")
	if __settings__.getSetting("ExtendON") ==    'true': AddItem("Расширенный поиск", "Extend")
	AddItem("Популярные", "Popular")
	if __settings__.getSetting("NewReleasesON") == 'true': AddItem("Новые релизы", "NewReleases")
	if __settings__.getSetting("NewON") ==         'true': AddItem("Недавние премьеры", "New")
	#AddItem("Новинки", "New2")
	if __settings__.getSetting("FutureON") ==    'true': AddItem("Самые ожидаемые", "Future")
	AddItem("Списки", "TopLists")
	AddItem("Персоны", "PersonList")
	if len(L)>0: AddItem("Буду смотреть", "Wish_list")
	if __settings__.getSetting("DebMod")=='true': 
		AddItem("Проверить список", "check")
		AddItem("Загрузка описаний", "load")
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

def Search(s=''):
	if s=="": 
		s=inputbox()
		add_history(s)
	if s!="": 
		SrcNavi(s)

def TopLists():
	for i in get_top_list():
		id=i[0]
		title=i[1]
		AddItem(title, "OpenTopList", id)

def PersonSearch():
	PS=inputbox()
	#link='https://www.kinopoisk.ru/index.php?first=no&what=&kp_query='+urllib.quote(PS)
	link='https://www.kinopoisk.ru/s/type/people/list/1/find/'+urllib.quote(PS)+'/?force-version=touch'
	#print link
	http = GET (link, 'https://www.kinopoisk.ru/?force-version=touch')
	#debug (http)
	ss='<p class="name">'
	es='<span class="year">'
	l1=mfindal(http,ss,es)
	for i in l1:
			#print i
			id=mfind(i, '/name/', '/sr').replace('/name/','')
			nm=fs(mfind(i, 'type="person">', '</a>').replace('type="person">',''))
			#print id+' '+nm
			if len(nm)>0 and len(id)>0 :AddItem(xt(nm), "PersonFilm", id,'', len(l1))
	#debug (http)

def Navigator():
	Cats=getList("CatList")
	Genres=getList("GenreList")
	Cantrys=getList("CantryList")
	Years=__settings__.getSetting("YearList")
	Old=__settings__.getSetting("OldList")
	Sort=__settings__.getSetting("SortList")
	Rating=__settings__.getSetting("RatingList")
	
	if Cats=="": Cats="[COLOR FFFFFF00] --[/COLOR]"
	if Genres=="": Genres="[COLOR FFFFFF00]  --[/COLOR]"
	if Cantrys=="": Cantrys="[COLOR FFFFFF00] --[/COLOR]"
	if Years=="": Years="--"
	if Old=="": Old="--"
	if Rating=="": Rating="> 7"
	if Sort=="": Sort="рейтингу Кинопоиска"
	
	AddItem("Категории: " +Cats,    "SelCat")
	AddItem("Жанры:      " +Genres,  "SelGenre")
	AddItem("Страны:      " +Cantrys, "SelCantry")
	AddItem("Год:             [COLOR FFFFFF00]" +Years+"[/COLOR]",   "SelYear")
	AddItem("Возраст:      [COLOR FFFFFF00]" +Old+"[/COLOR]",     "SelOld")
	AddItem("Рейтинг:      [COLOR FFFFFF00]" +Rating+"[/COLOR]",  "SelRating")
	AddItem("Порядок:      [COLOR FFFFFF00]по " +Sort+"[/COLOR]",    "SelSort")
	
	AddItem("[B][COLOR FF00FF00][ Искать ][/COLOR][/B]", "SrcNavi")

def Extend():
	Type=__settings__.getSetting("Type")
	Genres=getList("GenreList")
	Cantrys=getList("CantryList")
	Year=__settings__.getSetting("Year")
	
	if Type=="": Type="[COLOR FFFFFF00] --[/COLOR]"
	if Genres=="": Genres="[COLOR FFFFFF00]  --[/COLOR]"
	if Cantrys=="": Cantrys="[COLOR FFFFFF00] --[/COLOR]"
	if Year=="": Year="--"
	
	if Type=='film': SelType='[COLOR FFFFFF00] Фильм[/COLOR]'
	else: SelType='[COLOR FFFFFF00] Сериал [/COLOR]'
	AddItem("Тип:             " +SelType,    "SelType")
	AddItem("Жанры:      " +Genres,  "SelGenre")
	AddItem("Страны:      " +Cantrys, "SelCantry")
	AddItem("Год:               [COLOR FFFFFF00]" +Year+"[/COLOR]",   "SelYear2")
	
	AddItem("[B][COLOR FF00FF00][ Искать ][/COLOR][/B]", "ExtRez")

def Torrents_old(id, additm=True):
	offlist=[]
	if __settings__.getSetting("Serv1")=='false':  offlist.append('rutor')
	if __settings__.getSetting("Serv2")=='false':  offlist.append('fasttor')
	if __settings__.getSetting("Serv3")=='false':  offlist.append('freebfg')
	if __settings__.getSetting("Serv4")=='false':  offlist.append('bitru')
	if __settings__.getSetting("Serv5")=='false':  offlist.append('fileek')
	#if __settings__.getSetting("Serv6")=='false':  offlist.append('hdreactor')
	if __settings__.getSetting("Serv7")=='false':  offlist.append('lenta')
	if __settings__.getSetting("Serv8")=='false':  offlist.append('torrentby')
	if __settings__.getSetting("Serv9")=='false':  offlist.append('megapeer')
	#if __settings__.getSetting("Serv10")=='false': offlist.append('krasfs')
	if __settings__.getSetting("Serv11")=='false': offlist.append('findmagnet')
	if __settings__.getSetting("Serv12")=='false': offlist.append('kinozal')
	
	info=get_info(id)
	sys.path.append(os.path.join(addon.getAddonInfo('path'),"src"))
	ld=os.listdir(os.path.join(addon.getAddonInfo('path'),"src"))
	L2=[]
	Lz=[]
	for i in ld:
		off = True
		for sr in offlist:
			if sr in i: off = False
		if i[-3:]=='.py' and off: 
			try:
				exec ("import "+i[:-3]+"; skp="+i[:-3]+".Tracker()")
				#exec ("import "+i[:-3]+"; skp="+i[:-3]+".Tracker()")
				L = skp.Search(info)
			except: L=[]
			for D in L:
				print D
				url = D['url']
				try:    tor_title=D['title'].encode('utf-8').replace("«",'').replace("»",'').replace('"', '').replace("'", '').replace("`", '')
				except: tor_title=D['title'].replace("«",'').replace("»",'').replace('"', '').replace("'", '').replace("`", '')
				deb_print (lower(tor_title))
				ru_title=xt(info['title']).replace("«",'').replace("»",'').replace('"', '').replace("'", '').replace("`", '')
				deb_print (lower(ru_title))
				en_title=info['originaltitle'].replace("«",'').replace("»",'').replace('"', '').replace("'", '').replace("`", '')
				year=str(info['year'])
				try:year2=str(int(info['year'])+1)
				except:year2=year
				if __settings__.getSetting("SYear")=='true': SYear = False
				else: SYear = True
				#if 1==1:
				if (lower(ru_title) in lower(tor_title) or ru_title in tor_title) and (year in tor_title or year2 in tor_title or (info['type']!='' and SYear)):
					ftitle = lower(get_title(D['title'])).replace("«",'').replace("»",'').replace('"', '').replace("'", '').replace("`", '').strip()
					deb_print (ftitle+" ^ "+lower(ru_title))
					if ftitle == lower(ru_title).strip() or __settings__.getSetting("FTitle")=='false':
						deb_print ('Название соответствует')
						size = D['size']
						if 'MB' in size and '.' in size: size=size[:size.find('.')]
						size = size.replace('GB','').replace('MB','').strip()
						if size not in Lz or __settings__.getSetting("CutSize") == 'false':
							Lz.append(size)
							Z=D['size']
							if 'GB' in Z and Z.find('.') == 2: Z=Z[:3]+Z[4:]
							title=xt(mid(Z, 10))+" | "+xt(mids(D['sids'], 6))+" | "+xt(D['title'])
							title=get_label(xt(D['title']))+" "+title
							if additm:
								if __settings__.getSetting("SortLst") == 'true' and info['type']=='':
									pr=fnd(D)
									#ratio=str(get_rang(D))+" "
									if pr: title=FC(title, 'FEFFFFFF')
									else:  title=FC(title.replace("[COLOR F", "[COLOR 7"), 'FF777777')
								#print title
								AddItem(title, "OpenTorrent", id, url)
							L2.append(D)
				#print D
	return L2

def Torrents(id, additm=True):
	if __settings__.getSetting("Multimod")=='false': return Torrents_old(id, additm)
	offlist=[]
	if __settings__.getSetting("Serv1")=='false':  offlist.append('rutor')
	if __settings__.getSetting("Serv2")=='false':  offlist.append('fasttor')
	if __settings__.getSetting("Serv3")=='false':  offlist.append('freebfg')
	if __settings__.getSetting("Serv4")=='false':  offlist.append('bitru')
	if __settings__.getSetting("Serv5")=='false':  offlist.append('fileek')
	#if __settings__.getSetting("Serv6")=='false':  offlist.append('hdreactor')
	if __settings__.getSetting("Serv7")=='false':  offlist.append('lenta')
	if __settings__.getSetting("Serv8")=='false':  offlist.append('torrentby')
	if __settings__.getSetting("Serv9")=='false':  offlist.append('megapeer')
	#if __settings__.getSetting("Serv10")=='false': offlist.append('krasfs')
	if __settings__.getSetting("Serv11")=='false': offlist.append('findmagnet')
	if __settings__.getSetting("Serv12")=='false': offlist.append('kinozal')
	
	info=get_info(id)
	sys.path.append(os.path.join(addon.getAddonInfo('path'),"src"))
	ld=os.listdir(os.path.join(addon.getAddonInfo('path'),"src"))
	L2=[]
	Lz=[]
	L=[]
	
	tr_count = int(__settings__.getSetting("TrCount"))+2
	update_Lt('reset')
	total_threads=0
	
	for i in ld:
		off = True
		for sr in offlist:
			if sr in i: off = False
		
		if i[-3:]=='.py' and off: 
			create_thread({'i': i, 'info':info})
			total_threads+=1
			print 'total_threads '+str(total_threads)
			print 'life_threads  '+str(total_threads- len(Lthread))
			for t in range(20):
				if total_threads - len(Lthread) <= tr_count: break
				xbmc.sleep(100)
				print '= limit trad ='
				
	print 'total_threads '+str(total_threads)
	
	for t in range(20):
			print 'step '+str(t)
			print str(len(Lthread))+' to '+str(total_threads)
			if len(Lthread) == total_threads: break
			xbmc.sleep(1000)
	
	for Lst in Lthread:
			for st in Lst:
				L.append(st)
	
	for D in L:
				url = D['url']
				try:    tor_title=D['title'].encode('utf-8').replace("«",'').replace("»",'').replace('"', '').replace("'", '').replace("`", '')
				except: tor_title=D['title'].replace("«",'').replace("»",'').replace('"', '').replace("'", '').replace("`", '')
				deb_print (lower(tor_title))
				ru_title=xt(info['title']).replace("«",'').replace("»",'').replace('"', '').replace("'", '').replace("`", '')
				deb_print (lower(ru_title))
				en_title=info['originaltitle'].replace("«",'').replace("»",'').replace('"', '').replace("'", '').replace("`", '')
				year=str(info['year'])
				try:year2=str(int(info['year'])+1)
				except:year2=year
				if __settings__.getSetting("SYear")=='true': SYear = False
				else: SYear = True
				#if 1==1:
				if (lower(ru_title) in lower(tor_title) or ru_title in tor_title) and (year in tor_title or year2 in tor_title or (info['type']!='' and SYear)):
					ftitle = lower(get_title(D['title'])).replace("«",'').replace("»",'').replace('"', '').replace("'", '').replace("`", '').strip()
					deb_print (ftitle+" ^ "+lower(ru_title))
					if ftitle == lower(ru_title).strip() or __settings__.getSetting("FTitle")=='false':
						deb_print ('Название соответствует')
						size = D['size']
						if 'MB' in size and '.' in size: size=size[:size.find('.')]
						size = size.replace('GB','').replace('MB','').strip()
						if size not in Lz or __settings__.getSetting("CutSize") == 'false':
							Lz.append(size)
							Z=D['size']
							if 'GB' in Z and Z.find('.') == 2: Z=Z[:3]+Z[4:]
							season = get_season(tor_title)#+" | "
							title=xt(mid(Z, 10))+" | "+xt(mids(D['sids'], 6))+" | "+xt(D['title'])
							title=get_label(xt(D['title']))+" "+title
							if info['type']!='': title=season+" "+title
							if additm:
								if __settings__.getSetting("SortLst") == 'true' and info['type']=='':
									pr=fnd(D)
									#ratio=str(get_rang(D))+" "
									if pr: title=FC(title, 'FEFFFFFF')
									else:  title=FC(title.replace("[COLOR F", "[COLOR 7"), 'FF777777')
								AddItem(title, "OpenTorrent", id, url)
								print url
							L2.append(D)
				#print D
	return L2

def get_season(t):
	s=['[s','s', 'x', 'х', 'сезон ', ' сезон']
	L=[]
	for i in range(25):
		if i>9: si=str(i)
		else:   si='0'+str(i)
		L.append(s[0]+si)
		L.append(s[1]+si)
		L.append(si+s[2])
		L.append(si+s[3])
		L.append(s[4]+si)
		L.append(si+s[5])
		
	for i in range(9):
		L.append(str(i)+' сезон')
		L.append('сезон '+str(i))
		L.append(s[0]+str(i))
	
	for se in L:
		if se in lower(t): 
			for f in s:
				se = se.replace(f,'')
				if len(se)<2: se='0'+se
			return se
	return 'XX'

def get_label(text):
	text=lower(text)#.lower()
	#print text
	if 'трейлер'  in text: return FC('[ Трейл.]',    'FF999999')
	if ' кпк'     in text: return FC('[   КПК  ]',   'FFF8888F')
	if 'telesyn'  in text: return FC('[    TS    ]', 'FFFF2222')
	if 'telecin'  in text: return FC('[    TS    ]', 'FFFF2222')
	if 'camrip'   in text: return FC('[    TS    ]', 'FFFF2222')
	if ' ts'      in text: return FC('[    TS    ]', 'FFFF2222')
	if 'dvdscr'   in text: return FC('[    Scr   ]', 'FFFF2222')
	if ' 3d'      in text: return FC('[    3D    ]', 'FC45FF45')
	if '720'      in text: return FC('[  720p  ]',   'FBFFFF55')
	if '1080'     in text: return FC('[ 1080p ]',    'FAFF9535')
	if '2160'     in text: return FC('[ 2160p ]',    'FAF990FF')
	if 'blu-ray'  in text: return FC('[  BRay  ]',   'FF5555FF')
	if 'bdremux'  in text: return FC('[    BD    ]', 'FF5555FF')
	if ' 4k'      in text: return FC('[    4K    ]', 'FF5555FF')
	if 'bdrip'    in text: return FC('[ BDRip ]',    'FE98FF98')
	if 'drip'     in text: return FC('[ BDRip ]',    'FE98FF98')
	if 'hdrip'    in text: return FC('[ HDRip ]',    'FE98FF98')
	if 'webrip'   in text: return FC('[  WEB   ]',   'FEFF88FF')
	if 'WEB'      in text: return FC('[  WEB   ]',   'FEFF88FF')
	if 'web-dl'   in text: return FC('[  WEB   ]',   'FEFF88FF')
	if 'hdtv'     in text: return FC('[ HDTV ]',     'FEFFFF88')
	if 'tvrip'    in text: return FC('[    TV    ]', 'FEFFFF88')
	if 'satrip'   in text: return FC('[    TV    ]', 'FEFFFF88')
	if 'dvb '     in text: return FC('[    TV    ]', 'FEFFFF88')
	if 'dvdrip'   in text: return FC('[DVDRip]',     'FE88FFFF')
	if 'dvd5'     in text: return FC('[  DVD   ]',   'FE88FFFF')
	if 'xdvd'     in text: return FC('[  DVD   ]',   'FE88FFFF')
	if 'dvd-5'    in text: return FC('[  DVD   ]',   'FE88FFFF')
	if 'dvd-9'    in text: return FC('[  DVD   ]',   'FE88FFFF')
	if 'dvd9'     in text: return FC('[  DVD   ]',   'FE88FFFF')
	return FC('[   ????  ]', 'FFFFFFFF')

def get_title(t):
	n=999
	n1=t.find('/')
	n2=t.find('(')
	n3=t.find('[')
	if n1>0: n=n1
	if n2>0 and n2<n: n=n2
	if n3>0 and n3<n: n=n3
	ttl=t[:n].strip()
	print 'ttl:'+ttl
	return ttl

def get_item_name(url, ind=0):
	if 'btih:' in url:
		nt=url.find('&dn=')
		if nt>0:
			tmp=torr_link[nt+3:]
			kt=tmp.find('&')
			if kt>0:
				name=tmp[:kt]
			else:
				name=tmp
			return name
		else:
			return url
	else:
		torrent_data = GETtorr(url)
		if torrent_data != None:
			import bencode
			torrent = bencode.bdecode(torrent_data)
			try:
				L = torrent['info']['files']
				name=L[ind]['path'][-1]
			except:
				name=torrent['info']['name']
			return name
		else:
			return ' '


def save_strm(url, ind, id):
	info=get_info(id)
	pu='plugin://plugin.video.KinoPoisk.ru/?mode=Torrents&id='+str(id)
	xbmc.executebuiltin('Container.Update("plugin://plugin.video.tam/?mode=save_movie&purl='+urllib.quote_plus(pu)+'&url='+urllib.quote_plus(url)+ '&info=' + urllib.quote_plus(repr(info))+'")')

def check():
	deb_print ("check")
	tam_settings = xbmcaddon.Addon(id='plugin.video.tam')
	SaveDirectory = tam_settings.getSetting("SaveDirectory")
	if SaveDirectory=="":SaveDirectory=LstDir
	
	try:L=eval(__settings__.getSetting("W_list"))
	except: L=[]
	for id in L:
		deb_print (id)
		info=get_info(id)
		year=info["year"]
		name = info['originaltitle'].replace("/"," ").replace("\\"," ").replace("?","").replace(":","").replace('"',"").replace('*',"").replace('|',"")+" ("+str(info['year'])+")"
		deb_print (name)
		if os.path.isfile(os.path.join(fs_enc(SaveDirectory),fs_enc(name+".strm")))==False:
			L=Torrents(id, False)
			url=''
			rang=0
			for i in L:
				if fnd(i):
					rang_i=get_rang(i)
					if rang_i>rang:
						rang=rang_i
						deb_print (str(rang)+": "+i['title']+" "+i['size'])
						deb_print (i['url'])
						url=i['url']
			
			if url != "":
					#if __settings__.getSetting("NFO2")=='true': save_film_nfo(id)
					save_strm (url, 0, id)
		else:
			if __settings__.getSetting("AREM")=='true': # автоудаление из желаний
					try:Lt=eval(__settings__.getSetting("W_list"))
					except: Lt=[]
					Lt.remove(id)
					__settings__.setSetting("W_list", repr(Lt))


def alter(id, url=''):
		SaveDirectory = tam_settings.getSetting("SaveDirectory")
		if SaveDirectory=="":SaveDirectory=LstDir
		info=get_info(id)
		year=info["year"]
		name = info['originaltitle'].replace("/"," ").replace("\\"," ").replace("?","").replace(":","").replace('"',"").replace('*',"").replace('|',"")+" ("+str(info['year'])+")"
		L=Torrents(id, False)
		try:W_list=eval(__settings__.getSetting("W_list"))
		except: W_list=[]
		for i in L:
			newurl=i['url'].replace('new-ru.org','').replace('open-tor.org','')
			oldurl=url.replace('new-ru.org','').replace('open-tor.org','')
			if fnd(i) and newurl!=oldurl:
				if id in W_list:
					#if __settings__.getSetting("NFO2")=='true': save_film_nfo(id)
					save_strm (i['url'], 0, id)
				return i['url']

def autoplay(id):
		L=Torrents(id, False)
		url=''
		for i in L:
			if fnd(i): 
				url=i['url']
				break
		if url !='': play(url,0,id)
		else: 
			if len(L)== 0: showMessage("Кинопоиск", "Фильм не найден")
			else: showMessage("Кинопоиск", "Нет нужного качества")

def review(id):
	url='https://www.kinopoisk.ru/rss/comment-'+id+'.rss'
	url='https://www.kinopoisk.ru/film/'+id+'/reviews/'
	
	http=GET(url)
	#debug(http)
	ss='<meta itemprop="headline"'
	es='<p class="links">'
	L=mfindal(http,ss,es)
	#debug(L[0])
	Lt=[]
	Lp=[]
	for i in L:
		try:head=mfind(i,'content="','"')
		except: head=''
		
		plot = mfind(i,'reviewBody">','</p>').replace('<br />','').replace('</span>','')
		if head!='':
			Lt.append(rt(fs(head)))
			Lp.append(rt(fs(plot)))
	sel = xbmcgui.Dialog()
	r = sel.select("Рецензии:", Lt)
	if r >=0:
		text=Lp[r]
		heading=Lt[r]
		showText(heading, text)

def showText(heading, text):
	id = 10147
	xbmc.executebuiltin('ActivateWindow(%d)' % id)
	xbmc.sleep(500)
	win = xbmcgui.Window(id)
	retry = 50
	while (retry > 0):
		try:
			xbmc.sleep(10)
			retry -= 1
			win.getControl(1).setLabel(heading)
			win.getControl(5).setText(text)
			return
		except:
			pass

def fnd(D):
	try:
		BL=['Трейлер', "Тизер", 'трейлер', "тизер", 'ТРЕЙЛЕР', "ТИЗЕР"]
		if __settings__.getSetting("F_Qual") != "0":BL.extend([' TS','TeleSyn','TeleCin','TELECIN',' CAM',' CamRip','screen','Screen', 'звук из кинотеатра'])
		if __settings__.getSetting("F_Qual11")== 'false': BL.append("KOSHARA")
		if __settings__.getSetting("BlackList") != "":
			for bli in __settings__.getSetting("BlackList").split(","):
				BL.append(bli.strip())
		WL=[]
		if __settings__.getSetting("F_Qual1") == 'true': WL.append("dvdrip")
		if __settings__.getSetting("F_Qual2") == 'true': WL.append("webrip")
		if __settings__.getSetting("F_Qual3") == 'true': WL.append("web-dl")
		if __settings__.getSetting("F_Qual4") == 'true': WL.append("bdrip")
		if __settings__.getSetting("F_Qual5") == 'true': WL.append("hdrip")
		if __settings__.getSetting("F_Qual6") == 'true': WL.append("tvrip")
		if __settings__.getSetting("F_Qual7") == 'true': WL.append("hdtv")
		if __settings__.getSetting("F_Qual8") == 'true': WL.append("blu-ray")
		if __settings__.getSetting("F_Qual9") == 'true': WL.append("720p")
		if __settings__.getSetting("F_Qual10")== 'true': WL.append("1080p")
		
		if __settings__.getSetting("F_Qual") == '0': WL=[]

		size1 = int(__settings__.getSetting("F_Size1"))
		size2 = int(__settings__.getSetting("F_Size2"))
		if size2 == 0: size2 = 999
		
		b=0
		q=0
		z=0
		Title = D['title']
		try:Title=Title+' '+D['quality']
		except:pass
		
		try:Title=Title.encode('utf-8')
		except: Title=xt(Title)
		
		for i in BL:
			if Title.find(i)>0:b+=1
		
		if b==0:
			for i in BL:
				if lower(Title).find(lower(i))>0:b+=1
		
		
		if __settings__.getSetting("F_Qual") == "0":
			q=1
		else:
			for i in WL:
				if Title.lower().find(i)>0:q+=1
			
		if 'ГБ' in xt(D['size']) or 'GB' in xt(D['size']):
				szs=xt(D['size']).replace('ГБ','').replace('GB','').replace('|','').strip()
				sz=float(szs)
				if sz>size1 and sz<size2 : z=1
		else: z=0
		
		#print Title
		#if b <> 0: print 'Попал в Черный список'
		#if q == 0: print 'Низкое Качество'
		#if z == 0: print 'Не тот Размер'
		
		if b == 0 and q > 0 and z > 0:
			#print 'Файл найден'
			return True
		else: 
			return False
	except:
		return False

def get_rang(D):
	Title = D['title']
	try:Title=Title+' '+D['quality']
	except:pass
	try:Title=Title.encode('utf-8')
	except: Title=xt(Title)
	Title=Title.lower()
	ratio=0
	WL=[]
	if __settings__.getSetting("F_Qual1") == 'true' and "dvdrip"  in Title:   ratio+=40
	if __settings__.getSetting("F_Qual2") == 'true' and "webrip"  in Title:   ratio+=30
	if __settings__.getSetting("F_Qual3") == 'true' and "web-dl"  in Title:   ratio+=30
	if __settings__.getSetting("F_Qual4") == 'true' and "bdrip"   in Title:   ratio+=80
	if __settings__.getSetting("F_Qual5") == 'true' and "hdrip"   in Title:   ratio+=80
	if __settings__.getSetting("F_Qual6") == 'true' and "tvrip"   in Title:   ratio+=20
	if __settings__.getSetting("F_Qual7") == 'true' and "hdtv"    in Title:   ratio+=70
	if __settings__.getSetting("F_Qual8") == 'true' and "blu-ray" in Title:   ratio+=20
	
	if __settings__.getSetting("F_Qual9") == 'true' and '720p'    in Title:   ratio+=1000
	if __settings__.getSetting("F_Qual10")== 'true' and "1080p"   in Title:   ratio+=2000
	
	size1 = int(__settings__.getSetting("F_Size1"))
	size2 = int(__settings__.getSetting("F_Size2"))
	if size2 == 0: size2 = 10
	size=(size2-size1)/2+size1
	
	if 'ГБ' in xt(D['size']) or 'GB' in xt(D['size']):
			szs=xt(D['size']).replace('ГБ','').replace('GB','').replace('|','').strip()
			sz=float(szs)
			#print size
			#print sz
			#print abs(sz-size)
			#print '----'
			if   abs(sz-size)<1 : ratio+=900
			elif abs(sz-size)<2 : ratio+=800
			elif abs(sz-size)<3 : ratio+=700
			elif abs(sz-size)<4 : ratio+=600
			elif abs(sz-size)<5 : ratio+=500
			elif abs(sz-size)<6 : ratio+=400
			elif abs(sz-size)<7 : ratio+=300
			elif abs(sz-size)<8 : ratio+=200
			elif abs(sz-size)<9 : ratio+=100
	
	sids=D['sids']
	if len(sids)==1: ratio+=11
	if len(sids)==2: ratio+=44
	if len(sids)==3: ratio+=66
	if len(sids)==4: ratio+=88
	if len(sids)==5: ratio+=99
	if sids =='0': ratio-=500
	if sids =='1': ratio-=100
	if sids =='2': ratio-=50
	return ratio

def SetViewMode():
	n = int(__settings__.getSetting("ListView"))
	if n>0:
		xbmc.executebuiltin("Container.SetViewMode(0)")
		for i in range(1,n):
			xbmc.executebuiltin("Container.NextViewMode")

def History():
	try:L=eval(__settings__.getSetting("History"))
	except: L=[]
	for i in L:
		AddItem(i, 'HSearch', '0', i)
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

def add_history(t):
	try:L=eval(__settings__.getSetting("History"))
	except: L=[]
	if t not in L:
		NL=[]
		NL.append(t)
		NL.extend(L[:15])
		__settings__.setSetting("History", repr(NL))

try:    mode = urllib.unquote_plus(get_params()["mode"])
except: mode = None
try:    url = urllib.unquote_plus(get_params()["url"])
except: url = None
try:    info = eval(urllib.unquote_plus(get_params()["info"]))
except: info = {}
try:    id = str(get_params()["id"])
except: id = '0'
try:    ind = int(get_params()["ind"])
except: ind = 0


if mode == None:
	setList("CatList", Category)
	setList("GenreList", Genre)
	setList("CantryList", Cantry)
	__settings__.setSetting(id="YearList", value="")
	__settings__.setSetting(id="OldList", value="")
	__settings__.setSetting(id="SortList", value="")
	__settings__.setSetting(id="RatingList", value="")
	__settings__.setSetting(id="Type", value="film")
	__settings__.setSetting(id="Year", value="--")
	Root()

if mode == "Search":
	Search()
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == 'HSearch':
	Search(url)
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == 'History':
	History()

if mode == "Navigator":
	Navigator()
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == 'Extend':
	Extend()
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == "Next":
	SrcNavi("Next", url)
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == "Popular":
	SrcNavi("Popular")
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)


if mode == "New":
	SrcNavi("New")
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)
if mode == "NewReleases":
	SrcNavi("NewReleases")
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)
if mode == "New2":
	SrcNavi("New2")
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)


if mode == "Future":
	SrcNavi("Future")
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == "Recomend":
	SrcNavi("Recomend")
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == "PersonFilm":
	SrcNavi("PersonFilm")#+PeID
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == "Person":
	Person()
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == "PersonList":
	AddItem("[ Поиск ]", "PersonSearch")
	AddItem("[ Популярные ]", "PersonPopular")
	PersonList()
	xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == "PersonPopular":
	PersonPopular()
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == "PersonSearch": 
	PersonSearch()
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == "AddPerson": 
	AddPerson(info)

if mode == "RemovePerson": 
	RemovePerson(info)
	xbmc.executebuiltin("Container.Refresh()")
	
if mode == "SrcNavi":
	SrcNavi()
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == "ExtRez":
	SrcNavi('Extend')
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == "SelType":
	sel = xbmcgui.Dialog()
	L1=['Фильм','Сериал']
	L2=['film','serial']
	r = sel.select("Тип:", L1)
	__settings__.setSetting(id="Type", value=L2[r])

if mode == "SelCat":
	import SelectBox
	SelectBox.run("CatList")

if mode == "SelGenre":
	import SelectBox
	SelectBox.run("GenreList")

if mode == "SelCantry":
	import SelectBox
	SelectBox.run("CantryList")
	
if mode == "SelYear":
	sel = xbmcgui.Dialog()
	r = sel.select("Десятилетие:", Year)
	__settings__.setSetting(id="YearList", value=Year[r])

if mode == "SelYear2":
	sel = xbmcgui.Dialog()
	Ly=[]
	for i in range(1940,2022):
		Ly.append(str(i))
	Ly.append('--')
	Ly.reverse()
	r = sel.select("Год:", Ly)
	__settings__.setSetting(id="Year", value=str(Ly[r]))

if mode == "SelOld":
	sel = xbmcgui.Dialog()
	r = sel.select("Возраст:", Old)
	__settings__.setSetting(id="OldList", value=Old[r])

if mode == "SelSort":
	sel = xbmcgui.Dialog()
	r = sel.select("Десятилетие:", Sort)
	__settings__.setSetting(id="SortList", value=Sort[r])

if mode == "SelRating":
	sel = xbmcgui.Dialog()
	r = sel.select("Десятилетие:", Rating)
	__settings__.setSetting(id="RatingList", value=Rating[r])


if mode == "Torrents" or mode == "Torrents2":
	Torrents(id)
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.addSortMethod(handle, xbmcplugin.SORT_METHOD_LABEL)
	xbmcplugin.endOfDirectory(handle)
	xbmc.sleep(300)
	SetViewMode()
	#xbmc.executebuiltin("Container.SetViewMode(51)")

'''
if mode == "Torrents" or mode == "Torrents2":
	L=Torrents(id, False)
	#xbmc.executebuiltin('ActivateWindow(10025,"plugin://plugin.video.KinoPoisk.ru/?mode=Torrents&id='+id+'", return)')
	xbmc.executebuiltin('Container.Update("plugin://plugin.video.tam/?mode=open_torrent_list&L='+urllib.quote_plus(repr(L))+ '&info=' + urllib.quote_plus(repr(get_info(id)))+'")')
	#xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	#xbmcplugin.addSortMethod(handle, xbmcplugin.SORT_METHOD_LABEL)
	#xbmcplugin.endOfDirectory(handle)
	#xbmc.sleep(300)
	#SetViewMode()
'''

if mode == "OpenTorrent":
		OpenTorrent(url, id)
		xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
		xbmcplugin.addSortMethod(handle, xbmcplugin.SORT_METHOD_LABEL)
		xbmcplugin.endOfDirectory(handle)


if mode == "PlayTorrent":
	progressBar = xbmcgui.DialogProgress()
	progressBar.create('Кинопоиск', 'Запуск сохраненного файла')
	cancel=False
	for i in range (0,5):
		progressBar.update(20*i, '', '[B]Нажмите "Отмена" для выбора качества[/B]')
		xbmc.sleep(600)
		if progressBar.iscanceled():
					progressBar.update(0)
					cancel=True
					break
	progressBar.close()
	if cancel: 
		xbmc.executebuiltin('ActivateWindow(10025,"plugin://plugin.video.KinoPoisk.ru/?mode=Torrents&id='+id+'", return)')
		xbmc.executebuiltin("Container.Refresh()")
	else:
		play(url, ind, id)

if mode == "PlayTorrent2":
	play(url, ind, id)

if mode == "play_url2": #совместимость с 1.0
	url = urllib.unquote_plus(get_params()["torr_url"])
	play(url, ind, id)

if mode == "Add2List":
	try:L=eval(__settings__.getSetting("W_list"))
	except: L=[]
	if id not in L:
		L.append(id)
		__settings__.setSetting("W_list", repr(L))

if mode == "RemItem":
	try:L=eval(__settings__.getSetting("W_list"))
	except: L=[]
	L.remove(id)
	__settings__.setSetting("W_list", repr(L))
	xbmc.executebuiltin("Container.Refresh()")

if mode == "Wish_list":
	try:L=eval(__settings__.getSetting("W_list"))
	except: L=[]
	for id in L:
		info=get_info(str(id))
		rus=info["title"]
		AddItem(rus, 'Wish', id)
	xbmcplugin.endOfDirectory(handle)

if mode == "Wish":
	Torrents(id)
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.addSortMethod(handle, xbmcplugin.SORT_METHOD_LABEL)
	xbmcplugin.endOfDirectory(handle)
	xbmc.sleep(300)
	SetViewMode()
	#xbmc.executebuiltin("Container.SetViewMode(51)")

if mode == "update_info":
	update_info(id)

if mode == "TopLists":
	TopLists()
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == "OpenTopList":
	SrcNavi("OpenTopList")
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == "PlayTrailer":
	trailer=get_trailer(id)
	if trailer!='':
		info=get_info(str(id))
		cover=info['cover']
		title=info['title']
		listitem = xbmcgui.ListItem("trailer", path=trailer,iconImage=cover, thumbnailImage=cover)
		listitem.setInfo(type = "Video", infoLabels = get_labels(info))
		xbmc.Player().play(trailer, listitem)
		xbmcplugin.endOfDirectory(handle, False, False)

if mode == "Save_strm":
	#if __settings__.getSetting("NFO2")=='true': save_film_nfo(id)
	save_strm (url, 0, id)

if mode == "check":
	check()

if mode == "Review":
	review(id)

if mode == "Autoplay":
	autoplay(id)

if mode == "load":
	load()


c.close()

#print get_info_plus('1200818')
#import azpt