#!/usr/bin/python
# -*- coding: utf-8 -*-
# *   Copyright (C) 2016 TDW
# */
import os, cookielib, urllib2, urllib, urlparse, time
import xbmc, xbmcgui, xbmcplugin, xbmcaddon
import azpt
import ssl

siteUrl = 'www.lostfilm.tv'

h = int(sys.argv[1])
handle = int(sys.argv[1])

PLUGIN_NAME   = 'LostFilm3'

addon = xbmcaddon.Addon(id='plugin.video.LostFilm3')
__settings__ = xbmcaddon.Addon(id='plugin.video.LostFilm3')
CT = __settings__.getSetting("ConType")
if CT=="0": httpSiteUrl = 'http://' + siteUrl
else:httpSiteUrl = 'https://' + siteUrl
xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')

icon = os.path.join(addon.getAddonInfo('path'), 'icon.png')
thumb = os.path.join( addon.getAddonInfo('path'), "icon.png" )
icon2 = os.path.join( addon.getAddonInfo('path'), "cover.png" )
fanart = os.path.join( addon.getAddonInfo('path'), "fanart.jpg" )
LstDir = os.path.join( addon.getAddonInfo('path'), "playlists" )
dbDir = os.path.join( addon.getAddonInfo('path'), "db" )
ImgPath = os.path.join( addon.getAddonInfo('path'), "logo" )
playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)

ulogin = __settings__.getSetting("login")
upassw = __settings__.getSetting("password")
no_log = __settings__.getSetting("no_login")
if ulogin =="" or upassw == '' or no_log=='true': fcookies = os.path.join(addon.getAddonInfo('path'), 'cookies.txt')
else: fcookies = xbmc.translatePath(os.path.join(xbmc.translatePath("special://masterprofile/"),"addon_data","plugin.video.LostFilm3", 'cookies.txt'))



def construct_request(params):
	return '%s?%s' % (sys.argv[0], urllib.urlencode(params))

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

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


def fs(s):
	if s == None: return None
	try: s=s.decode('windows-1251')
	except: pass
	try: s=s.encode('utf-8')
	except: pass
	return s
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;',' '), ('&mdash;','-')]
	for i in L:
		x=x.replace(i[0], i[1])
	return x

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 GETpac(target, referer='http://lostfilm.tv/', post=None):
	try:
		req = urllib2.Request(url = target, data = post)
		req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.173')
		resp = urllib2.urlopen(req)
		http = resp.read()
		resp.close()
		return http
	except Exception, e:
		#xbmc.log( '[%s]: GET EXCEPT [%s]' % (addon_id, e), 4 )
		print target
		showMessage('HTTP ERROR', e, 5000)

def GETvpn():
	import httplib
	conn = httplib.HTTPConnection("antizapret.prostovpn.org")
	conn.request("GET", "/proxy.pac", headers={"User-Agent": 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.173'})
	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("immunicity") == "4":
	import socks
	from stem import Signal
	from stem.control import Controller

def set_new_ip():
	# Необходимо для смены сессии ТОРа, т.к. иногда сессии или с большой задержкой, или не работаеют. Но это очень редко
	with Controller.from_port(port=9051) as controller:
		controller.authenticate()
		controller.signal(Signal.NEWNYM)


#-------------------------------------------------------------------------------
# get cookies from last session

cj = cookielib.LWPCookieJar(fcookies)
try:cj.load()
except:pass
hr  = urllib2.HTTPCookieProcessor(cj)

if __settings__.getSetting("immunicity") == "1":
	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, "https": prx})
		opener = urllib2.build_opener(proxy_support, hr)
		print "Immunicity "+prx
	except:
		opener = urllib2.build_opener(hr)
		print "NO Proxy"
	
elif __settings__.getSetting("immunicity") == "2":
	prx=__settings__.getSetting("Proxy")
	if prx.find('http')<0: prx="http://"+prx
	context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
	proxy_support = urllib2.ProxyHandler({"http" : prx, "https": prx})
	opener = urllib2.build_opener(proxy_support, hr, urllib2.HTTPSHandler(context=context))
	print "Proxy "+__settings__.getSetting("Proxy")
elif __settings__.getSetting("immunicity") == "4":
	import socksipyhandler
	prx=__settings__.getSetting("ProxyTor")
	if prx.find('://')>=0: prx=(prx[prx.rfind('//')+2:]).replace('/', '')
	(addr, port) = prx.split(':')
	opener = urllib2.build_opener(socksipyhandler.SocksiPyHandler(socks.PROXY_TYPE_SOCKS5, addr, int(port)), hr)
	print "Proxy "+__settings__.getSetting("Proxy")
elif __settings__.getSetting("immunicity") == "6":
	prx='http://127.0.0.1:8095'
	context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
	proxy_support = urllib2.ProxyHandler({"http" : prx, "https": prx})
	opener = urllib2.build_opener(proxy_support, hr, urllib2.HTTPSHandler(context=context))
	print "Proxy TAM"
else:
	opener = urllib2.build_opener(hr)
	print "NO Proxy"

urllib2.install_opener(opener)

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

def proxy(url):
	if '127.0.0.1' not in url: url='http://127.0.0.1:8095/proxy/'+url
	return url


def GET(target, referer='http://lostfilm.tv/', post=None):
	decr = False
	if __settings__.getSetting("immunicity") == "5" and '?q=' not in target: 
		target = azpt.convert(target)
		decr = True
	#target=target.replace('https:', 'http:')
	#target=proxy(target)
	try:
		req = urllib2.Request(url = target, data = post)
		req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.173')
		resp = urllib2.urlopen(req)
		http = resp.read()
		resp.close()
		if decr : http=azpt.decoder(http)
		return http
	except Exception, e:
		#xbmc.log( '[%s]: GET EXCEPT [%s]' % (addon_id, e), 4 )
		print repr(target)
		showMessage('HTTP ERROR', e, 5000)


def play(url, ind=0, id='0', cse='(0,0,0)'):
	if ind<0: ind = get_index(url, cse)
	if ind==None: ind = 0
	#engine=__settings__.getSetting("Engine")
	play_tam(url, ind)
	H=__settings__.getSetting("History")
	if H=='': HL=[]
	else: HL=eval(H)
	if cse.replace(".00","") not in HL and cse!='(0,0,0)':
		HL.append(cse.replace(".00",""))
		__settings__.setSetting("History", repr(HL))
	xbmc.executebuiltin("Container.Refresh")

def play_tam(url, ind):
	purl ="plugin://plugin.video.tam/?mode=play&url="+ urllib.quote_plus(url)+"&ind="+str(ind)
	item = xbmcgui.ListItem(path=purl)
	try:item.setInfo(type = "Video", infoLabels = {})
	except: pass
	item.setProperty('IsPlayable', 'true')
	xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)

def favor(id=''):
	try:L=eval(__settings__.getSetting("FAV"))
	except: L=[]
	if id == "":
		return L
	else:
		if id in L:
			L.remove(id)
		else:
			L.append(id)
		__settings__.setSetting("FAV", repr(L))
		return L

def muf(r, id):
	L=favor()
	if id in L: r='[COLOR ffffffff]'+r+'[/COLOR]'
	return(r)


def get_item_name(url, ind):
	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 OpenTorrent(url, id='0', cse='(0,0,0)'):
	print cse
	if eval(cse)[2]!='999': return play(url,-1,0,cse)
	print '==OpenTorrent=='
	print url
	torrent_data = GETtorr(url)
	if torrent_data != None:
		import bencode
		torrent = bencode.bdecode(torrent_data)
		cover = icon#get_info(id)['cover']
		try:
			L = torrent['info']['files']
			ind=0
			for i in L:
				name=ru(i['path'][-1])
				#size=i['length']
				listitem = xbmcgui.ListItem(name, iconImage=cover, thumbnailImage=cover)
				listitem.setInfo(type = "Video", infoLabels = {'cover':cover, 'title': name})
				listitem.setProperty('IsPlayable', 'true')
				uri = sys.argv[0]+'?mode=PlayTorrent&id='+id+'&ind='+str(ind)+'&url='+urllib.quote_plus(url)
				xbmcplugin.addDirectoryItem(handle, uri, listitem)
				ind+=1
			print '=1='
			
		except:
				print '=2='
				ind=0
				name=torrent['info']['name']
				listitem = xbmcgui.ListItem(name, iconImage=cover, thumbnailImage=cover)
				listitem.setProperty('IsPlayable', 'true')
				#listitem.addContextMenuItems([('[B]Сохранить фильм(STRM)[/B]', 'Container.Update("plugin://plugin.video.KinoPoisk.ru/?mode=Save_strm&id='+id+'&url='+urllib.quote_plus(url)+'")'),])
				uri =sys.argv[0]+'?mode=PlayTorrent&id='+id+'&ind='+str(ind)+'&url='+urllib.quote_plus(url)+'&cse='+urllib.quote_plus(cse)
				e=-1#int(eval(cse)[2])-1
				print play
				play(url,e,id, cse)
				#xbmcplugin.addDirectoryItem(handle, uri, listitem)

def get_index(url, cse='(0,0,0)'):
	try:
		print url
		e=int(eval(cse)[2])
		if e<10: ep='e0'+str(e)
		else:    ep='e'+str(e)
		torrent_data = GETtorr(url)
		if torrent_data != None:
			import bencode
			torrent = bencode.bdecode(torrent_data)
			try:
				L = torrent['info']['files']
				ind=0
				for i in L:
					name=ru(i['path'][-1])
					if ep in name.lower(): return ind
					ind+=1
				return e-1
			except:
				return 0
		else:
			return 0
	except:
		print 'ERR get_index. set index 0'
		return 0



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


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)')
			resp = urllib2.urlopen(req)
			return resp.read()
	except Exception, e:
			print 'HTTP ERROR ' + str(e)
			return None

def GETtorr_2(target):
	Login()
	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)')
			resp = urllib2.urlopen(req)
			fl = open(os.path.join( addon.getAddonInfo('path'),'tmp.torrent'), "wb")
			fl.write(resp.read())
			fl.close()
			return os.path.join( addon.getAddonInfo('path'),'tmp.torrent')
			#return resp.read()
	except Exception, e:
			print 'HTTP ERROR ' + str(e)
			return None

def debug(s):
	fl = open(os.path.join(ru(addon.getAddonInfo('path')),"test.txt"), "w")
	fl.write(s)
	fl.close()

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 GETimg(target, referer=None, post=None):
	lfimg=os.listdir(ru(LstDir))
	nmi =os.path.basename(target)

	if nmi in lfimg and os.path.getsize(os.path.join(ru(LstDir),nmi))>0:
		return os.path.join( ru(LstDir),nmi)
	elif __settings__.getSetting("Picture") == "true":
		try:
			req = urllib2.Request(url = target, data = post)
			req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.173')
			resp = urllib2.urlopen(req)
			fl = open(os.path.join( ru(LstDir),nmi), "wb")
			fl.write(resp.read())
		#resp.close()
			fl.close()
			return os.path.join( ru(LstDir),nmi)
		except Exception, e:
			#xbmc.log( '[%s]: GET EXCEPT [%s]' % (addon_id, e), 4 )
			return target
			print 'HTTP ERROR ' + str(e)
	else:
		return target

def GETtorr2(target, referer=None, post=None):
	lfimg=os.listdir(ru(LstDir))
	#print target
	nmi =target.replace('http://tracktor.in/td.php?s=','')

	if nmi in lfimg and os.path.getsize(os.path.join(ru(LstDir),nmi))>0:
		return os.path.join( ru(LstDir),nmi)
	else:
		try:
			req = urllib2.Request(url = target, data = post)
			req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.173')
			resp = urllib2.urlopen(req)
			fl = open(os.path.join( ru(LstDir),nmi), "wb")
			fl.write(resp.read())
		#resp.close()
			fl.close()
			return os.path.join( ru(LstDir),nmi)
		except Exception, e:
			#xbmc.log( '[%s]: GET EXCEPT [%s]' % (addon_id, e), 4 )
			return target
			print 'HTTP ERROR ' + str(e)


def get_HTML(url, post = None, ref = None, get_redirect = False):
    #url=proxy(url)
    if url.find('http')<0 :
        if CT=="0": url='http:'+url
        else: url='https:'+url
    #url="http://translate.googleusercontent.com/translate_c?u="+url
    
    request = urllib2.Request(url, post)

    host = urlparse.urlsplit(url).hostname
    if ref==None:
        try:
           ref='http://'+host
        except:
            ref='localhost'

    request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.173')
    request.add_header('Host',   host)
    request.add_header('Accept', 'text/html, application/xhtml+xml, */*')
    request.add_header('Accept-Language', 'ru-RU')
    request.add_header('Referer',             ref)
    request.add_header('Content-Type','application/x-www-form-urlencoded')

    try:
        f = urllib2.urlopen(request)
    except IOError, e:
        if hasattr(e, 'reason'):
           print('We failed to reach a server.')
        elif hasattr(e, 'code'):
           print('The server couldn\'t fulfill the request.')
        return 'We failed to reach a server.'

    if get_redirect == True:
        html = f.geturl()
    else:
        html = f.read()

    return html


def Login():
	if __settings__.getSetting("immunicity") == "5":  return True
	if __settings__.getSetting("no_login") == "true": return True
	
	try:uptime=int(__settings__.getSetting("uptime"))
	except:uptime=0
	print time.time()-uptime
	if time.time()-uptime<3600: return True
	else:
		print 'Проверка авторизации'
		rec=GET(httpSiteUrl+'/feedback/')
		if '<a href="/reg"' not in rec:
							print 'Аторизация не требуется'
							return True
	print 'Начало авторизации'
	url1 = httpSiteUrl+'/ajaxik.php'
	login = __settings__.getSetting("login")#.replace('@','%40')
	passw = __settings__.getSetting("password")
	if login =="" or passw == '': showMessage('lostfilm', "Проверьте логин и пароль", times = 50000)

	values = {
				'mail' : login,
				'pass' : passw,
				'rem'  : 1,
				'type' : 'login',
				'act'  : 'users'
		}
	post = urllib.urlencode(values)
	#print post
	html = get_HTML(url1, post, httpSiteUrl+'/login')
	#debug (html)
	print 'Успешно авторизованы'
	cj.save(ignore_discard=True)
	__settings__.setSetting("uptime", str(time.time()))
	print 'Сохранено'
	return True
	
	#-- ok


def AddItem(Title = "", mode = "", info={}, url='', total=15, cse='(0,0,0)'):
			#info=get_info(id)
			try:id = info['id']
			except: id='0'
			try:link = info['link']
			except: link=''
			try:e = info['episode']
			except: e ='0'
			try:s = info['season']
			except: s ='0'
			if id == '0':
				try:cover = info['cover']
				except: cover = os.path.join( addon.getAddonInfo('path'), "cover.png" )
				fanart = os.path.join( addon.getAddonInfo('path'), "fanart.jpg" )
			else:
				cover = 'http://static.lostfilm.tv/Images/'+id+'/Posters/shmoster_s1.jpg'
				if __settings__.getSetting("Cover") == '0':       cover = 'http://static.lostfilm.tv/Images/'+id+'/Posters/shmoster_s1.jpg'
				if __settings__.getSetting("Cover") == '1':       cover = 'http://static.lostfilm.tv/Images/'+id+'/Posters/image.jpg'
				if __settings__.getSetting("Cover") == '2':       cover = 'http://static.lostfilm.tv/Images/'+id+'/Posters/icon.jpg'
				if mode=="Releases":
					if __settings__.getSetting("Preview") == '0':
						if __settings__.getSetting("Art") == '0': fanart = 'http://static.lostfilm.tv/Images/'+id+'/Posters/image.jpg'
						if __settings__.getSetting("Art") == '1': fanart = 'http://static.lostfilm.tv/Images/'+id+'/Posters/poster.jpg'
					if __settings__.getSetting("Preview") == '1': fanart = 'http://static.lostfilm.tv/Images/'+id+'/Posters/e_'+s+'_'+e+'.jpg'
					if __settings__.getSetting("Preview") == '2': fanart = 'http://static.lostfilm.tv/Images/'+id+'/Posters/icon.jpg'
				else:
						if __settings__.getSetting("Art") == '0': fanart = 'http://static.lostfilm.tv/Images/'+id+'/Posters/image.jpg'
						if __settings__.getSetting("Art") == '1': fanart = 'http://static.lostfilm.tv/Images/'+id+'/Posters/poster.jpg'
			
			#info['castandrole']=[]
			
			if __settings__.getSetting("immunicity") != "0":# and __settings__.getSetting("immunicity") != "4": тут картинки качает коди через web-proxy
				if 'http' in fanart: fanart=fanart.replace('lostfilm.tv','lostfilm.tw') #azpt.convert(fanart)
				if 'http' in cover:  cover =cover.replace('lostfilm.tv','lostfilm.tw') #azpt.convert(cover)
			
			listitem = xbmcgui.ListItem(Title, iconImage=cover, thumbnailImage=fanart)
			try:listitem.setInfo(type = "Video", infoLabels = info)
			except:
				pass
				#debug(repr(info))
			try: listitem.setArt({ 'poster': cover, 'fanart' : fanart})
			except: pass
			listitem.setProperty('fanart_image', fanart)
			
			purl = sys.argv[0] + '?mode='+mode+'&id='+id+'&cse='+cse+'&link='+urllib.quote_plus(link)
			if url !="": purl = purl +'&url='+urllib.quote_plus(url)
			
			try:
				lf_name=info['originaltitle']
				lf_url='plugin://plugin.video.LostFilm3/?mode=TC&link='+urllib.quote_plus(link)+'&title='+urllib.quote_plus(lf_name)
			except: pass
			
			if mode=="Getlist":
				listitem.addContextMenuItems([('[B]Отслеживать в ТС[/B]', 'Container.Update("plugin://plugin.video.torrent.checker/?mode=add&url='+urllib.quote_plus(lf_url)+'&name='+lf_name+'&manual=0")'), ('[B]Фавориты[/B]', 'Container.Update("plugin://plugin.video.LostFilm3/?mode=FAV&id='+id+'")'), ('[B]Обновить описание[/B]', 'Container.Update("plugin://plugin.video.LostFilm3/?mode=UpInfo&link='+urllib.quote_plus(link)+'")')])
			
			folder=True
			
			if mode=="OpenTorrent" and e !="999":
				listitem.setProperty('IsPlayable', 'true')
				folder=False
			
			if __settings__.getSetting("Quality") != '0' and mode=="Releases":# and 'сезон.' not in xt(Title):
				listitem.addContextMenuItems([('[B]Обновить список[/B]', 'Container.Refresh'), ('[B]Выбрать качество[/B]', 'Container.Update("plugin://plugin.video.LostFilm3/?mode=Releases2&cse='+urllib.quote_plus(cse)+'&id='+id+'&link='+urllib.quote_plus(link)+'")'), ('[B]Все серии[/B]', 'Container.Update("plugin://plugin.video.LostFilm3/?mode=Getlist&id='+id+'&link='+urllib.quote_plus(link)+'")'),('[B]Отслеживать в ТС[/B]', 'Container.Update("plugin://plugin.video.torrent.checker/?mode=add&url='+urllib.quote_plus(lf_url)+'&name='+lf_name+'&manual=0'+'")'),])
				
				if 'сезон[' not in xt(Title):
					listitem.setProperty('IsPlayable', 'true')
					purl = sys.argv[0] + '?mode=Autoplay&id='+id+'&cse='+urllib.quote_plus(cse)
					folder=False
				else:
					purl = sys.argv[0] + '?mode=Releases&cse='+urllib.quote_plus(cse)+'&id='+id
			elif mode=="Releases":
				listitem.addContextMenuItems([('[B]Обновить список[/B]', 'Container.Refresh'),('[B]Все серии[/B]', 'Container.Update("plugin://plugin.video.LostFilm3/?mode=Getlist&id='+id+'&link='+urllib.quote_plus(link)+'")'),('[B]Отслеживать в ТС[/B]', 'Container.Update("plugin://plugin.video.torrent.checker/?mode=add&url='+urllib.quote_plus(lf_url)+'&name='+lf_name+'&manual=0'+'")'),])
			elif mode == 'Serials':
				listitem.addContextMenuItems([('[B]Загрузить список сериалов[/B]', 'Container.Update("plugin://plugin.video.LostFilm3/?mode=UpSerials&id='+id+'&link='+urllib.quote_plus(link)+'")'),])
			try:
				if cse.replace(".00","") in eval(__settings__.getSetting("History")): listitem.select(True)
			except:
				pass
			
			xbmcplugin.addDirectoryItem(handle, purl, listitem, folder, total)

def TC(link, name):
	Login()
	sys.path.append(os.path.join(xbmc.translatePath("special://home/"),"addons","plugin.video.torrent.checker"))
	import updatetc
	LD=updatetc.file_list(name)
	
	L=Get_episode(link)
	info=get_info(link)
	id = info['id']
	for i in L:
				cse=i['cse']
				c,s,e=eval(cse)
				nm =i['nm']+'.strm'
				title=i['title']
				cover = 'http://static.lostfilm.tv/Images/'+id+'/Posters/e_'+s+'_'+e+'.jpg'
				if nm not in LD:
						L2=Releases(cse, '0', False)
						q=['dfth','hd','1080','sd','dfth']
						quality=q[int(__settings__.getSetting("Quality"))]
						uri=L2[0][1]
						pic=L2[0][2]
						
						for j in L2:
							pic=j[2]
							lbl=j[0]
							if '720' in lbl: pic+=' hd'
							if quality in pic: uri=j[1]
						ind=int(eval(cse)[2])-1
						updatetc.save_strm(name, nm, uri, ind)
						if s=='999': updatetc.save_nfo(name, nm.replace('.strm',''),'0' , e, {'title':xt(title), 'cover':cover})


def autoplay(cse, id='0'):
		L=Releases(cse, "0", False)
		q=['dfth','hd','1080','sd']
		qs=int(__settings__.getSetting("Quality"))
		
		url=L[0][1]
		pic=L[0][2]
		
		if qs == 4: # вызов диалога
			lbl=[]
			for j in L:
				lbl.append(j[0])
			sel = xbmcgui.Dialog()
			r = sel.select("Качество:", lbl)
			if r < 0 : return
			url=L[r][1]
			pic=L[r][2]
		else:       # автовыбор
			quality=q[qs]
			for i in L:
				pic=i[2]
				lbl=i[0]
				if '720' in lbl: pic+=' hd'
				if quality in pic: url=i[1]
		e=str(eval(cse)[2])
		if e=="99" or e=="999":
			OpenTorrent(url, id)
			xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
			xbmcplugin.addSortMethod(handle, xbmcplugin.SORT_METHOD_LABEL)
			xbmcplugin.endOfDirectory(handle)
		else:
			e=-1#int(eval(cse)[2])-1
			play(url,e,id,cse)


def get_desc(link,s,e):
	sid=link+'s'+s+'e'+e
	try:
		desc=xt(get_inf_db(sid))
		return desc
	except:
		url=httpSiteUrl + link+'/season_'+s+'/episode_'+e+'/'
		
		hp=GET(url)
		desc=hp[hp.find('style="height:20px;overflow:hidden">')+36:hp.find('<div style="margin-top:-10px;">')].replace('</div>', '').replace('\t', '')
		
		if len(desc) < 3000 and len(desc) > 30:
			add_to_db(sid, desc)
			return desc
		else:
			return ''


def get_cast(link, roles=False):
	url=httpSiteUrl + link+'/cast/type_1'
	hp=GET(url)
	hp=hp[hp.find('<div class="center-block margin-left">'):]
	ss='<a href="/persons'
	es='</a>'
	L=mfindal(hp, ss, es)
	LL=[]
	n=0
	for j in L:
		n+=1
		actor = ''
		role = ''
		img = ''
		url = ''
		L2=j.splitlines()
		for i in L2:
			if 'name-ru' in  i: actor = i[i.find('">')+2:i.find('</div>')]
			if 'role-ru' in  i: role  = i[i.find('">')+2:i.find('</div>')]
			if 'autoload' in i: img   = 'http:'+i[i.find('//static.'):i.find('" />')]
			if '/persons' in i: url   = httpSiteUrl + i[i.find('/persons'):i.find('" class=')]
		if roles: LL.append(actor+' | '+role)
		else:     LL.append({'actor':actor,'role':role,'cover':img,'url':url})
		if n>8: return LL
	return LL

def get_director(link):
	url=httpSiteUrl + link+'/cast/type_2'
	hp=GET(url)
	hp=hp[hp.find('<div class="center-block margin-left">'):]
	ss='<a href="/persons'
	es='</a>'
	L=mfindal(hp, ss, es)
	director=''
	for j in L:
		img = ''
		url = ''
		L2=j.splitlines()
		for i in L2:
			if 'name-ru' in  i: director += i[i.find('">')+2:i.find('</div>')]+", "
			if 'autoload' in i: img   = 'http:'+i[i.find('//static.'):i.find('" />')]
			if '/persons' in i: url   = httpSiteUrl + i[i.find('/persons'):i.find('" class=')]
			if len(director)> 30: return director
	return director

def get_info(link, up=False):
	try:
		if up: rem_inf_db(link)
		info=eval(xt(get_inf_db(link)))
		return info
	except:
		#try:
			url=httpSiteUrl + link
			
			hp=GET(url)
			L=hp.splitlines()
			
			#tmp=hp[hp.find('webkit-user-select: none">')+26:]
			#plot = tmp[:tmp.find('</div>')]
			if 'og:description" content="' in hp: plot = mfind(hp,'og:description" content="','" />')
			else: plot = ""
			
			ru_title =''
			en_title =''
			studio =''
			year =''
			genre =''
			premiered=''
			id='0'
			
			for i in L:
				try:
					if 'title-ru'               in i: ru_title =i[i.find('">')+2:i.find('</')]
					if 'title-en'               in i: en_title =i[i.find('">')+2:i.find('</')]
					if 'сериалы телеканала'     in i:   studio =i[i.find('">')+2:i.find('</a>')]
					if 'Перейти к первой серии' in i:     year =i[i.find('</a>')-4:i.find('</a>')]
					if 'Перейти к первой серии' in i: premiered=i[i.find('">')+2:i.find('</a>')]
					if 'сериалы жанра'          in i:   genre +=i[i.find('">')+2:i.find('</a>')]+", "
					if 'main_poster'            in i:       id =i[i.find('/Images/')+8:i.find('/Posters/')]
				except:
					pass
			
			try:    castandrole=get_cast(link, True)
			except: castandrole=[]
			
			try:    director = get_director(link)
			except: director = ''
			
			info = {"title": ru_title,
					"tvshowtitle": ru_title,
					"originaltitle":en_title,
					"year":year,
					"premiered":premiered,
					"genre":genre,
					"studio":studio,
					"director":director,
					"castandrole":castandrole,
					"plot":rt(plot),
					"id":id,
					"link":link
					}
			
			#try: Ls=eval(xt(get_inf_db('dblist')))
			#except: Ls=[]
			#if link not in Ls and :
			#	Ls.append(link)
			#	rem_inf_db('dblist')
			#	add_to_db('dblist', repr(Ls))
			#print link
			#print info
			add_to_db(link, repr(info))
			return info
		#except:
		#	return {"title": '',
		#			"originaltitle":'',
		#			"year":'year',
		#			"genre":'genre',
		#			"studio":'studio',
		#			"director":'director',
		#			"cover":'',
		#			"fanart":'',
		#			"plot":'',
		#			"id":id
		#			}

def clear_text(t):
	L=mfindal(t,'<a class=', '">')
	for i in L:
		t=t.replace(i,"")
	
	if len(t)>1:
		t=t.replace('<font size="2">','')
		t=t.replace('<font face="Verdana">','')
		t=t.replace('<font color="#000000">','')
		t=t.replace('<font face="Arial','')
		t=t.replace('<font color="#1f1f1f">','')
		t=t.replace('<div class="bb" align="justify">',"")
		t=t.replace('</a>','').replace('">','')
		t=t.replace('<br>','')
		t=t.replace('<br','')
		t=t.replace('</b>','')
		t=t.replace('<b>','')
		t=t.replace('<br />','')
		t=t.replace('<br /','')
		t=t.replace('/>','')
		t=t.replace('&nbsp;',"")
		t=t.replace('<strong class="bb',"")
		t=t.replace('<i class="bb',"")
		t=t.replace('<div class="bb',"")
		t=t.replace('align="',"")
		t=t.replace('</strong>',"")
		t=t.replace('</i>','')
		t=t.replace('"',"”")
		t=t.replace('&amp;',"&")
		try:
			if t[0]==chr(10):  t=t[1:]
		except: pass
		t=t.strip()
		#print t
	return t

def get_cover(id):
	try:
		url=httpSiteUrl + '/details.php?id='+id
		http=fs(GET(url))
		ss='http&#58'
		es='" alt="" /><br />'
		if es not in http: es='" alt="" /> <br />'
		cover=mfindal(http,ss,es)[0].replace('&#58;',':').replace('&#46;','.')
		return cover
	except:
		return ''

def US(t):
	Ls=get_Ls()
	for link in Ls:
		info=get_info(link)
		title=info["title"]
		if lower(t) in lower(title):
			AddItem("[B]"+xt(title)+"[/B]", "Getlist", info, '', len(Ls))

def Serials():
	Ls=get_Ls()
	#Ls.reverse()
	for link in Ls:
			try:info=get_info(link)
			except:
				info={"title": link.replace('/series/',''),
					"originaltitle":'',
					"year":'year',
					"genre":'genre',
					"studio":'studio',
					"director":'director',
					"cover":'',
					"fanart":'',
					"plot":'',
					"id":id
					}
			title=muf(info["title"], info['id'])
			
			AddItem("[B]"+xt(title)+"[/B]", "Getlist", info, '', len(Ls))

def get_Ls(fastup = True):
	mp=45
	ext=0
	try: Ls=eval(xt(get_inf_db('dblist')))
	except: Ls=[]
	if __settings__.getSetting("immunicity") == "5": return Ls
	
	Lt=[]
	for n in range (0,mp):
		try:
			#print n
			url = xt(httpSiteUrl + '/ajaxik.php')
			post='act=serial&type=search&o='+str(n*10)+'&s=3&t=0'
			
			ajax = get_HTML(url, post, httpSiteUrl)#'http://www.lostfilm.tv'
			d = eval(ajax.replace('\\/','/').replace(':"',':u"').replace("true",'"true"').replace("false",'"false"').replace("null",'"0"').replace("title_orig",'originaltitle'))
			print d
			L=d["data"]
			if L==[]:
				rem_inf_db('dblist')
				add_to_db('dblist', repr(Ls))
				return Ls
			
			if n==0: L.reverse()
			for i in L:
				link=i["link"]
				if link not in Ls:
					if n==0:
						Ls.insert(0, link)
					else:
						Ls.append(link)
				else: ext+=1
			
			if ext >0 and fastup:
					rem_inf_db('dblist')
					add_to_db('dblist', repr(Ls))
					return Ls
		except:
			print 'error load new '
			return Ls
			
	rem_inf_db('dblist')
	add_to_db('dblist', repr(Ls))
	return Ls

def NEW_page(n):
	try: Ls=eval(xt(get_inf_db('dblist')))
	except: Ls=[]
	upd = False
	
	url=httpSiteUrl + '/new/page_'+str(n)
	ht=GET(url)
	http=ht[ht.find('class="row"'):].replace('\t','')#.replace('</div>','"}').replace('<div class=','{').replace('">','":"')#.replace('','').replace('','').replace('','').replace('','')
	ss='class="row"'
	es='hor-breaker dashed'
	L=mfindal(http, ss, es)
	LL=[]
	for j in L:
		#debug (j)
		L2=j.splitlines()
		season=0
		episode=0
		id=''
		id2=''
		name_ru=''
		name_en=''
		ep_name_ru=''
		ep_name_en=''
		data_ru='01.01.1970'
		data_en='01.01.1970'
		url=''
		#print j
		for i in L2:
			if 'text-decoration:none' in i:
								episode    =i[i.find('episode_')+8:i.find('/" ')]
								if '/additional' in i:
									link   =i[i.find('/series/'):i.find('/additional')]
									season ='999'
								else:
									link   =i[i.find('/series/'):i.find('/season')]
									season =i[i.find('season_')+7:i.find('/ep')]
			if 'class="alpha"' in i:
				if 'Ru:' in i:  data_ru    =i[i.find('Ru:')+4:i.find('</div>')]
				else:			ep_name_ru =i[i.find('">')+2:i.find('</div>')]
			if 'class="beta"' in i:
				if 'Eng:' in i: data_en    =i[i.find('Eng:')+5:i.find('</div>')]
				else:			ep_name_en =i[i.find('">')+2:i.find('</div>')]
			if 'Posters' in i:  id         =i[i.find('Images/')+7:i.find('/Posters')]
			if 'name-ru' in i:  name_ru    =i[i.find('">')+2:i.find('</div>')]
			if 'name-en' in i:  name_en    =i[i.find('">')+2:i.find('</div>')]
			
		#fanart = 'http://static.lostfilm.tv/Images/'+id+'/Posters/image.jpg'#'/Posters/e_'+season+'_'+episode+'.jpg'
		#cover  = 'http://static.lostfilm.tv/Images/'+id+'/Posters/shmoster_s1.jpg'
		
		# превью эпизода '//static.lostfilm.tv/Images/276/Posters/e_2_2.jpg'
		# обложка сезона '//static.lostfilm.tv/Images/276/Posters/shmoster_s1.jpg'
		# мелкий фанарт  '//static.lostfilm.tv/Images/228/Posters/image.jpg'
		# крупный фанарт '//static.lostfilm.tv/Images/276/Posters/poster.jpg'
		# иконка сериала '//static.lostfilm.tv/Images/301/Posters/icon.jpg'
		
		
		try:    info=get_info(link)
		except: info={}
		#info['cover']=fpic
		#info['fanart']=  fanart
		info['title']=   ep_name_ru
		info['episode']= episode
		info['season']=  season
		info['id']=  id
		
		LL.append (info)
		if Ls!=[] and link not in Ls:
			print link
			Ls.append(link)
			upd = True
	if upd:
		rem_inf_db('dblist')
		add_to_db('dblist', repr(Ls))
	
	return LL


def NEW():
	AddItem("[B]Все сериалы[/B]", "Serials", {}, "")
	if __settings__.getSetting("immunicity") == "4": set_new_ip()
	#n=2
	n=int(__settings__.getSetting("Pages"))+1
	for p in range (1,n+1):
		L=NEW_page(p)
		for i in L:
			try:
				se=i['season']+"."+i['episode']
				if i['season'] == '999': se="0."+i['episode']
				title = i['tvshowtitle']
				sr_title = i['title']
				cse=repr((i['id'],i['season'],i['episode']))
				AddItem(se+" [B][COLOR FFFFFFFF]"+xt(title)+":[/COLOR][/B] "+xt(sr_title), "Releases", i, '', 10*n, cse)
			except:
				print 'LF: err NEW episode'

def Releases(cse, id='0', add=True):
	import pomdb
	c,s,e=eval(cse)
	try:
		D=pomdb.get_info(c+'/'+s+'/'+e)
		print D
		if time.time()-float(D['tm'])< 86400 or __settings__.getSetting("immunicity") == "5":
			L   = D['list']
			LL  = []
			for i in L:
				info = i[3]
				tor  = azpt.original(i[1])
				if add: AddItem("[B]"+xt(i[0])+":[/B]", "OpenTorrent", info, tor, 3, cse)
				LL.append(i)
			return LL
	except:
		pass
		print 'NOT in DB'
	
	if __settings__.getSetting("immunicity") == "5":
		showMessage('lostfilm.tv', 'Временно недоступно для WEB-proxy')
		return []
	
	Login()
	
	#'http://n.retre.org/v3/index.php?c=451&s=1&e=10&u=1916803&h=f1db54b2153f66be00ddbebee9ecb132&n=1&newbie='
	trurl = xt( httpSiteUrl+'/v_search.php?c='+c+'&s='+s+'&e='+e)
	#print trurl
	if __settings__.getSetting("CLFR") == 'false': t=fs(GET(trurl))
	else: t=None
	
	if t==None:
		import cloudscraper
		d_proxy = False
		if __settings__.getSetting("immunicity") == "1" or __settings__.getSetting("immunicity") == "2":
			d_proxy = { "http": prx, "https": prx}
		scraper = cloudscraper.CloudScraper(debug=False)
		scraper.cookies.update(cj)
		scraper.get(trurl, proxies=d_proxy)
		t=scraper.get(trurl, proxies=d_proxy).text
		__settings__.setSetting("CLFR", 'true') 
	#debug(t)
	#print t
	if 'log in first' in t:
		showMessage('lostfilm.tv', 'Ошибка авторизации')
		return
	if 'a.retre.org' in t: nurl=mfind(t,'url=','">')
	elif 'n.retre.org' in t: nurl=mfind(t,'url=','">')
	elif 'insearch.site' in t: nurl=mfind(t,'url=','">')
	else:                  nurl=t[t.find('("http://retre')+2:t.find('");')]
	print nurl
	#http=GET(nurl)#.replace('/v3/','/v2/')
	#if __settings__.getSetting("immunicity") != "0" and __settings__.getSetting("immunicity") != "4": http=azpt.decoder(GET(azpt.convert(nurl)))
	#else: 
	http=GET(nurl)
	
	http=http.replace(chr(10),"").replace("    "," ").replace("  "," ").replace("  "," ").replace("\t","")
	ss='inner-box--label'
	es='</div> </div>'
	L=mfindal(http, ss, es)
	LL=[]
	LLL=[]
	for i in L:
		if len(i)>20:
			#print i
			ss='box--label">'
			es='</div> <div class="inner-box--link'
			pic=i[i.find(ss)+12:i.find(es)].lower()
			
			fpic="http://retre.org/img/search_"+pic+".png"
			if 'a.retre' in i: fpic="http://a.retre.org/img/search_"+pic+".png"
			if 'n.retre' in i: fpic="http://a.retre.org/img/search_"+pic+".png"
			
			ss='http://tracktor'
			if 'a.tracktor' in i: ss='http://a.tracktor'
			if 'n.tracktor' in i: ss='http://n.tracktor'
			es='">'
			tt=i[i.find(ss):]
			tor=tt[:tt.find(es)]
			
			label=i[i.find('Видео: ')+12:i.find('Перевод:')]
			
			info={}
			info['cover']=fpic
			info['title']=label
			info['episode']=e
			info['season']=s
			
			tor_orig=tor
			
			#if __settings__.getSetting("immunicity") = "0" and __settings__.getSetting("immunicity") != "4": tor=azpt.convert(tor)
			
			if add: AddItem("[B]"+xt(label)+":[/B]", "OpenTorrent", info, tor, 3, cse)
			LL.append([label, tor, fpic, info])
			LLL.append([label, tor_orig, fpic, info])
			
	if LL!=[] and __settings__.getSetting("immunicity") != "5": 
		try: pomdb.add(c+'/'+s+'/'+e, {'list': LLL, 'tm': time.time()})
		except: pass
	return LL

def Getlist(link):
		xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
		Login()
		url=httpSiteUrl+link+'/seasons'
		#print url
		http=GET(url)
		ss='serie-block'
		es='</table>'
		L=mfindal(http,ss,es) # сезоны
		info=get_info(link)
		id=info['id']
		for j in L:
			jj=j[:j.find('class="clr"')]
			s_title=jj[jj.find('<h2>')+4:jj.find('</h2>')]
			s=s_title.replace(' сезон','')
			info['title']=s_title
			if 'copyrightedEpisode' in jj: cse="('"+id+"','"+s+"','999')"
			elif  'PlayEpisode'     in jj: cse=jj[jj.find('PlayEpisode')+11:jj.find(')"></')+1]
			elif  'data-code='      in jj: cse="('"+mfind(jj,'data-code="','"').replace('-',"','")+"','999')"
			else: cse=''
			#print j
			if cse!='': AddItem("  [B][COLOR FF00FF00]"+xt(s_title)+"[/COLOR][/B]", "Releases", info, '',len(L), cse)
			elif s_title!='': AddItem("  [B][COLOR FF00FF00]"+xt(s_title)+"[/COLOR][/B]", "Releases_off", info, '',len(L), cse)
			
			ss='<tr'
			es='</tr>'
			Lep=mfindal(j,ss,es) # серии
			for i in Lep:
				#print '===='
				#print i
				try:
					info_ep=eval(repr(info))
					if '/season_' in i:
						if '/season_' in i: s  = i[i.find('/season_')+8:i.find('/ep')]
						else: s  = '999'
						e  =i[i.find('/episode_')+9:i.find("/',false)")]
						if 'copyrightedEpisode' in i:
							cse="('"+id+"','"+s+"','"+e+"')"
						elif  'PlayEpisode'     in i:
							cse=i[i.find('PlayEpisode')+11:i.find(')"></')+1]
					else:
						print 'no avt'
						cse="('"+mfind(i,'data-code="','"').replace('-',"','")+"')"
						#cse="('"+i[i.find('data-code="')+11:i.find('"></div>')].replace('-','"','"')+"')"
						
						print cse
						id,s,e = eval(cse)
						
					#cse=repr((i['id'],s,e))
					tmp=i[i.find('<td class="gamma'):i.find('<span class="gray')]
					#print tmp
					if 'not-available' in i:	sr_title = tmp[tmp.find('">')+2:tmp.find('<br>')].replace("\t","").replace("\n","")
					else:						sr_title = tmp[tmp.find('<div>')+5:tmp.find('<br />')].replace("\t","").replace("\n","")
					#print sr_title
					premiered=i[i.find('">Ru: ')+6:i.find('<br /><span class="gray')]
					try:rat =i[i.find('mark-green-box">')+16:i.find('mark-green-box">')+19].replace('<','').replace('/','')
					except:rat=""
					
					#print premiered
					try:id = eval(cse)[0]
					except:pass
						
					if s=="999": se="0."+e
					else: se=s+"."+e
					
						
					info_ep['title']=sr_title
					info_ep['episode']=e
					info_ep['season']=s
					info_ep['premiered']=premiered
					
					try:   info_ep['rating']=float(rat)
					except:info_ep['rating']=0
					
					if e != "999" and __settings__.getSetting("Desc") == 'true':
						desc=get_desc(link,s,e)
						info_ep['plot']=desc
					
					if 'not-available' in i:	item_title = "[COLOR AAFF5555]"+se+" - [B]"+xt(sr_title)+"[/B] (" + premiered+")[/COLOR]"
					else:						item_title = se+" - [B]"+xt(sr_title)+"[/B]"
					AddItem(item_title, "Releases", info_ep, '',len(L), cse)
				except:
					pass


def Get_episode(link):
		url=httpSiteUrl+link+'/seasons'
		
		http=GET(url)
		ss='serie-block'
		es='</table>'
		L=mfindal(http,ss,es) # сезоны
		LL=[]
		info=get_info(link)
		name=info['originaltitle']
		id = info['id']
		for j in L:
			ss='<tr>'
			es='</tr>'
			Lep=mfindal(j,ss,es) # серии
			for i in Lep:
				#debug (i)
				try:
					if '/season_' in i: s  = i[i.find('/season_')+8:i.find('/ep')]
					else: s  = '00'
					e  =i[i.find('/episode_')+9:i.find("/',false)")]
					if 'copyrightedEpisode' in i: cse="('"+id+"','"+s+"','"+e+"')"
					elif  'PlayEpisode'     in i: cse=i[i.find('PlayEpisode')+11:i.find(')"></')+1]
					else: cse=''
					tmp=i[i.find('<td class="gamma'):i.find('<span class="gray')]
					sr_title = tmp[tmp.find('<div>')+5:tmp.find('<br />')].replace("\t","").replace("\n","")
					if e!="999":
						if len(s)<2:s="0"+s
						if len(e)<2:e="0"+e
						nm=name+".s"+s+".e"+e
					
					if cse!='':LL.append({'nm':nm,'cse':cse, 'title':sr_title})
				except:
					pass
		return LL


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

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

def rem_inf_db(n):
		tor_id="n"+n.replace('/',"_").replace('-',"_")
		try:
			cu.execute("DROP TABLE "+tor_id+";")
			c.commit()
		except:
			print 'ERR DROP TABLE'
			pass



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")




params = get_params()
mode     = 'New'
url      = '0'
title    = ''
ref      = ''
img      = ''
id       = '0'
cse      = '(0,0,0)'
info  = {}

try: mode  = urllib.unquote_plus(params["mode"])
except: pass

try: url  = urllib.unquote_plus(params["url"])
except: pass

try: dir  = urllib.unquote_plus(params["dir"])
except: dir = "."

try: title  = urllib.unquote_plus(params["title"])
except: pass

try: cse  = urllib.unquote_plus(params["cse"])
except: pass

try: img  = urllib.unquote_plus(params["img"])
except: pass

try: id  = urllib.unquote_plus(params["id"])
except: pass

try: link  = urllib.unquote_plus(params["link"])
except: link  = ""

try:    ind = int(get_params()["ind"])
except: ind = 0

try: info  = eval(urllib.unquote_plus(params["info"]))
except: pass




if mode == None or mode == "New":
	NEW()
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)
	try: get_Ls()
	except: pass

elif mode == 'Serials':
	Serials()
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	if __settings__.getSetting("Sort") == '0': xbmcplugin.addSortMethod(handle, xbmcplugin.SORT_METHOD_LABEL)
	xbmcplugin.endOfDirectory(handle)

elif mode == 'UpSerials':
	get_Ls(False)

elif mode == 'UpInfo':
	#print link
	get_info(link, True)

elif mode == 'OpenTorrent':
	OpenTorrent(url, id, cse)
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.addSortMethod(handle, xbmcplugin.SORT_METHOD_LABEL)
	xbmcplugin.endOfDirectory(handle)

elif mode == 'Releases' or mode == 'Releases2':
	Releases(cse, id)
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.addSortMethod(handle, xbmcplugin.SORT_METHOD_LABEL)
	xbmcplugin.endOfDirectory(handle)

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


if mode == 'Getlist':
	Getlist(link)
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)
	xbmc.sleep(300)
	SetViewMode()


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

if mode == "FAV":
	favor(id)
	xbmc.executebuiltin('Container.Refresh')

if mode == "TC":
	TC(link, title)

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

c.close()