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

# *  Copyright (C) 2018 TDW

import xbmc, xbmcgui, xbmcplugin, xbmcaddon, os, urllib, urllib2, time
import animedia

PLUGIN_NAME   = 'animedia.tv'
siteUrl = 'tt.animedia.tv'
httpSiteUrl = 'http://' + siteUrl
handle = int(sys.argv[1])
addon = xbmcaddon.Addon(id='plugin.video.animedia.tv')
__settings__ = xbmcaddon.Addon(id='plugin.video.animedia.tv')
xbmcplugin.setContent(int(sys.argv[1]), 'movies')

icon  = os.path.join( addon.getAddonInfo('path'), 'icon.png')
dbDir = addon.getAddonInfo('path')
LstDir = 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 fs(s):return s.decode('windows-1251').encode('utf-8')
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:
		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 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))

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

Cat=animedia.type.keys()
Genre=animedia.genres.keys()
Year=animedia.years.keys()
Year.sort()
Year.reverse()
Ongoing=['Любой','Сейчас выходит','Вышедшие']
Sort=['Популярные','Новые']


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

def save_strm(url, ind=0, id='0'):
		if __settings__.getSetting("SaveMagnet")=='true' and 'magnet' not in url: url=t2m(url)
		info=get_info(str(id))
		SaveDirectory = __settings__.getSetting("SaveDirectory")
		if SaveDirectory=="":SaveDirectory=LstDir
		name = info['originaltitle'].replace("/"," ").replace("\\"," ").replace("?","").replace(":","").replace('"',"").replace('*',"").replace('|',"")+" ("+str(info['year'])+")"
		
		uri = sys.argv[0] + '?mode=PlayTorrent'
		uri = uri+ '&url='+urllib.quote_plus(url)
		uri = uri+ '&ind='+str(ind)
		uri = uri+ '&id='+str(id)
		
		fl = open(os.path.join(fs_enc(SaveDirectory),fs_enc(name+".strm")), "w")
		fl.write(uri)
		fl.close()
		
		xbmc.executebuiltin('UpdateLibrary("video", "", "false")')

def save_film_nfo(id):
		info=get_info(str(id))
		title=info['title']
		fanart=info['fanart']
		cover=info['cover']
		year=info['year']
		#try: fanarts=info["fanarts"]
		#except: 
		fanarts=[fanart,cover]
		#posters=get_posters(id)
		#fanarts.extend(posters)
		
		try:plot=info['plot']
		except:plot=''
		try:rating=info['rating']
		except:rating=0
		try:originaltitle=info['originaltitle']
		except:originaltitle=title
		
		try:duration=info["duration"]
		except:duration=''
		try:genre=info["genre"].replace(', ', '</genre><genre>')
		except:genre=''
		try:studio=info["studio"]
		except:studio=''
		
		try: director=info["director"]
		except: director=''
		try:cast=info["cast"]
		except:cast=[]
		try: actors=info["actors"]
		except: actors={}
		
		name = info['originaltitle'].replace("/"," ").replace("\\"," ").replace("?","").replace(":","").replace('"',"").replace('*',"").replace('|',"")+" ("+str(info['year'])+")"
		cn=name.find(" (")
		#if cn>0:
		#	name=name[:cn]
		#	rus=1
		#else: rus=0
		
		#trailer=get_trailer(id)
		
		SaveDirectory = __settings__.getSetting("SaveDirectory")
		if SaveDirectory=="":SaveDirectory=LstDir
		
		nfo='<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>'+chr(10)
		nfo+='<movie>'+chr(10)
		
		nfo+="	<title>"+title+"</title>"+chr(10)
		nfo+="	<originaltitle>"+originaltitle+"</originaltitle>"+chr(10)
		nfo+="	<genre>"+genre+"</genre>"+chr(10)
		nfo+="	<studio>"+studio+"</studio>"+chr(10)
		nfo+="	<director>"+director+"</director>"+chr(10)
		nfo+="	<year>"+str(year)+"</year>"+chr(10)
		nfo+="	<plot>"+plot+"</plot>"+chr(10)
		nfo+='	<rating>'+str(rating)+'</rating>'+chr(10)
		nfo+='	<runtime>'+duration+' min.</runtime>'+chr(10)
		
		nfo+="	<fanart>"+chr(10)
		for fan in fanarts:
			nfo+="		<thumb>"+fan+"</thumb>"+chr(10)
		nfo+="		<thumb>"+cover+"</thumb>"+chr(10)
		nfo+="	</fanart>"+chr(10)
		
		nfo+="	<thumb>"+cover+"</thumb>"+chr(10)
		
		for actor in cast:
			nfo+="	<actor>"+chr(10)
			nfo+="		<name>"+actor+"</name>"+chr(10)
			#try:
			#	aid=actors[actor]
			#	actor_img="http://st.kp.yandex.net/images/actor_iphone/iphone360_"+aid+".jpg"
			#	nfo+="		<thumb>"+actor_img+"</thumb>"+chr(10)
			#except: pass
			nfo+="	</actor>"+chr(10)
		
		nfo+="</movie>"+chr(10)
		
		fl = open(os.path.join(fs_enc(SaveDirectory),fs_enc(name+".nfo")), "w")
		fl.write(nfo)
		fl.close()



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 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 t2m(url):
	import bencode, hashlib
	r = GETtorr(url)#requsets.get(url, stream=True).raw.read()
	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


def chek_in():
	try:
		argv2=sys.argv[2]
		
		if xbmc.getInfoLabel('ListItem.FileName') == '': 
			if '.strm' in argv2: 
				FileName = argv2[argv2.find('title=')+6:argv2.find('.strm')+5].replace('+',' ')
			else: 
				id = argv2[argv2.find('&id=')+4:]
				info=get_info(str(id))
				FileName = info['originaltitle'].replace("/"," ").replace("\\"," ").replace("?","").replace(":","").replace('"',"").replace('*',"").replace('|',"")+" ("+str(info['year'])+")"+".strm"
		else:   FileName = xbmc.getInfoLabel('ListItem.FileName')
		
		if xbmc.getInfoLabel('ListItem.Path') == '':     Path = __settings__.getSetting("SaveDirectory")
		else:                                            Path = xbmc.getInfoLabel('ListItem.Path')
		try: 
			FileName = FileName.decode('utf-8')
			Path = Path.decode('utf-8')
		except: pass
		k_db = KodiDB(FileName, Path, sys.argv[0] + sys.argv[2])
		k_db.PlayerPreProccessing()
		return k_db
	except: 
		return None


def chek_out(k_db):
	k_db.PlayerPostProccessing()
	xbmc.sleep(300)
	xbmc.executebuiltin('Container.Refresh')
	xbmc.sleep(200)
	if not xbmc.getCondVisibility('Library.IsScanningVideo'):
		xbmc.executebuiltin('UpdateLibrary("video", "", "false")')


def play(url, ind=0, id='0'):
	#print url
	if 'magnet' in url: 
		if '&hashinfo=' in url: url = url[:url.find('&hashinfo=')]
		engine=__settings__.getSetting("Engine2")
		if engine=="0": play_t2h (url, ind, __settings__.getSetting("DownloadDirectory"))
		if engine=="1": play_elementum(url, ind)
		if engine=="2": play_ace_proxy(url, ind, id)
		#if engine=="3": play_ace(url, ind)
	else:
		engine=__settings__.getSetting("Engine")
		if engine=="0": play_ace (url, ind)
		if engine=="1": play_t2h (url, ind, __settings__.getSetting("DownloadDirectory"))
		if engine=="2": play_yatp(url, ind)
		if engine=="3": play_torrenter(url, ind)
		if engine=="4": play_elementum(url, ind)
		if engine=="5": play_xbmctorrent(url, ind)
		if engine=="6": play_ace_proxy(url, ind, id)


def play_ace_proxy(url, ep=0, id='0'):
	inf=get_info(id)
	title=inf['title']
	cover=inf['cover']
	progressBar = xbmcgui.DialogProgress()
	progressBar.create('ACE Stream', 'Запуск')
	try:ASE_start()
	except: pass
	srv=__settings__.getSetting("p2p_serv")#'127.0.0.1'
	prt=__settings__.getSetting("p2p_port")#'6878'
	if 'btih:' in url:
		CID=mfind(url+'&', 'btih:', '&')
		as_url='http://'+srv+':'+prt+'/ace/getstream?infohash='+CID+"&format=json&_idx="+str(ep)
	else:
		as_url='http://'+srv+':'+prt+'/ace/getstream?url='+url+"&format=json&_idx="+str(ep)
	
	if __settings__.getSetting("p2p_dlnk") == 'true':
		xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem(path=as_url.replace("&format=json", "")))
		return
	
	#print as_url
	if as_url!='':
		json=eval(GET(as_url).replace('null','"null"'))["response"]
		progressBar.update(0, 'ACE Stream', 'Контент найден', "")
		stat_url=json["stat_url"]
		stop_url=json["command_url"]+'?method=stop'
		purl=json["playback_url"]
		
		progressBar.update(0, 'ACE Stream', 'Подключение', "")
		while not xbmc.abortRequested:
			xbmc.sleep(300)
			j=eval(GET(stat_url).replace('null','"null"'))["response"]
			if j=={}:
				pass
				progressBar.update(0, 'ACE Stream', 'Ожидание', "")
			else:
				status=j['status']
				if status=='dl': break
				try:
					download=j['downloaded']
					progress=j['total_progress']
					#if progress>90: break
					seeds=j['peers']
					speed=j['speed_down']
					progressBar.update(progress*10, xt('Предварительная буферизация: '+str(download/1024/1024)+" MB"), "Сиды: "+str(seeds), "Скорость: "+str(speed)+' Kbit/s')
				except: pass
			if progressBar.iscanceled():
				progressBar.update(0)
				progressBar.close()
				GET(stop_url)
				return
		
		progressBar.update(0)
		progressBar.close()
		GET(stat_url)
		print purl
		item = xbmcgui.ListItem(path=purl, iconImage=cover, thumbnailImage=cover)
		item.setInfo('video', inf)
		xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
		#xbmc.Player().play(purl)
		xbmc.sleep(5000)
		
		while not xbmc.abortRequested and xbmc.Player().isPlaying():
						xbmc.sleep(500)
		GET(stop_url)
	else:
		showMessage('Кинопоиск','Поток не найден')

def play_ace(torr_link, ind=0):
	if 'btih:' in torr_link:
		torr_link=mfind(torr_link, 'btih:', '&')
		type_link='INFOHASH'
	else:
		type_link='TORRENT'
		
	try:
		title=get_item_name(torr_link, ind)
		from TSCore import TSengine as tsengine
		TSplayer=tsengine()
		out=TSplayer.load_torrent(torr_link, type_link)
		#print out
		if out=='Ok': TSplayer.play_url_ind(int(ind),title, icon, icon, True)
		TSplayer.end()
		return out
	except: 
		return '0'

def play_t2h(uri, file_id=0, DDir=""):
	#try:
		print 'play_t2h'
		print uri
		sys.path.append(os.path.join(xbmc.translatePath("special://home/"),"addons","script.module.torrent2http","lib"))
		from torrent2http import State, Engine, MediaType
		print 'import ok'
		progressBar = xbmcgui.DialogProgress()
		from contextlib import closing
		if DDir=="": DDir=os.path.join(xbmc.translatePath("special://home/"),"userdata")
		progressBar.create('Torrent2Http', 'Запуск')
		# XBMC addon handle
		# handle = ...
		# Playable list item
		# listitem = ...
		# We can know file_id of needed video file on this step, if no, we'll try to detect one.
		# file_id = None
		# Flag will set to True when engine is ready to resolve URL to XBMC
		ready = False
		# Set pre-buffer size to 15Mb. This is a size of file that need to be downloaded before we resolve URL to XMBC 
		pre_buffer_bytes = 15*1024*1024
		
		if progressBar.iscanceled():
					progressBar.update(0)
					progressBar.close()
					return

		engine = Engine(uri, download_path=DDir, enable_dht=True, dht_routers=["router.bittorrent.com:6881","router.utorrent.com:6881"], user_agent = 'uTorrent/2200(24683)')
		with closing(engine):
			# Start engine and instruct torrent2http to begin download first file, 
			# so it can start searching and connecting to peers  
			engine.start(file_id)
			progressBar.update(0, 'Torrent2Http', 'Загрузка торрента', "")
			while not xbmc.abortRequested and not ready:
				if progressBar.iscanceled():
					progressBar.update(0)
					progressBar.close()
					return

				xbmc.sleep(500)
				status = engine.status()
				# Check if there is loading torrent error and raise exception 
				engine.check_torrent_error(status)
				# Trying to detect file_id
				if file_id is None:
					# Get torrent files list, filtered by video file type only
					files = engine.list(media_types=[MediaType.VIDEO])
					# If torrent metadata is not loaded yet then continue
					if files is None:
						continue
					# Torrent has no video files
					if not files:
						break
						progressBar.close()
					# Select first matching file                    
					file_id = files[0].index
					file_status = files[0]
				else:
					# If we've got file_id already, get file status
					file_status = engine.file_status(file_id)
					# If torrent metadata is not loaded yet then continue
					if not file_status:
						continue
				if status.state == State.DOWNLOADING:
					# Wait until minimum pre_buffer_bytes downloaded before we resolve URL to XBMC
					if file_status.download >= pre_buffer_bytes:
						ready = True
						break
					#print file_status
					#downloadedSize = status.total_download / 1024 / 1024
					getDownloadRate = status.download_rate / 1024 * 8
					#getUploadRate = status.upload_rate / 1024 * 8
					getSeeds = status.num_seeds
					
					progressBar.update(100*file_status.download/pre_buffer_bytes, xt('Предварительная буферизация: '+str(file_status.download/1024/1024)+" MB"), "Сиды: "+str(getSeeds), "Скорость: "+str(getDownloadRate)[:4]+' Mbit/s')#
					
				elif status.state in [State.FINISHED, State.SEEDING]:
					#progressBar.update(0, 'T2Http', 'We have already downloaded file', "")
					# We have already downloaded file
					ready = True
					break
				
				if progressBar.iscanceled():
					progressBar.update(0)
					progressBar.close()
					break
				# Here you can update pre-buffer progress dialog, for example.
				# Note that State.CHECKING also need waiting until fully finished, so it better to use resume_file option
				# for engine to avoid CHECKING state if possible.
				# ...
			progressBar.update(0)
			progressBar.close()
			if ready:
				# Resolve URL to XBMC
				item = xbmcgui.ListItem(path=file_status.url)
				xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
				xbmc.sleep(3000)
				xbmc.sleep(3000)
				# Wait until playing finished or abort requested
				while not xbmc.abortRequested and xbmc.Player().isPlaying():
					xbmc.sleep(500)
	#except: pass


def play_yatp(url, ind):
	purl ="plugin://plugin.video.yatp/?action=play&torrent="+ urllib.quote_plus(url)+"&file_index="+str(ind)
	item = xbmcgui.ListItem(path=purl)
	xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)

def play_torrenter(url, ind):
	purl ="plugin://plugin.video.torrenter/?action=playSTRM&url="+ urllib.quote_plus(url)+"&file_index="+str(ind)
	item = xbmcgui.ListItem(path=purl)
	xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)

def play_elementum(url, ind):
	purl ="plugin://plugin.video.elementum/play?uri="+ urllib.quote_plus(url)+"&index="+str(ind)
	item = xbmcgui.ListItem(path=purl)
	xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)

def play_xbmctorrent(url, ind):
	purl ="plugin://plugin.video.xbmctorrent/play/"+ urllib.quote_plus(url)+"/"+str(ind)
	item = xbmcgui.ListItem(path=purl)
	xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)

def unlock(url):
	try:
		import xbmcaddon
		__settings__ = xbmcaddon.Addon(id='plugin.video.animedia.tv')
		if __settings__.getSetting("ProxyON")=='true': Proxy = True
		else: Proxy = False
	except:
		Proxy = True
	if Proxy:
		url='http://127.0.0.1:8095/proxy/'+url
	return url

def GET(url,Referer = 'http://www.KinoPoisk.ru/'):
	deb_print ('KP GET '+url)
	#if __settings__.getSetting("unlock")=='true' and 'torrentino' in url: return GETcameleo(url)
	try:
		req = urllib2.Request(url)
		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('Accept', '*/*')
		req.add_header('Accept-Language', 'ru,en;q=0.9')
		req.add_header('Referer', Referer)
		req.add_header('x-requested-with', 'XMLHttpRequest')
		response = urllib2.urlopen(req)
		link=response.read()
		response.close()
		return link
	except:
		try:
			import requests
			s = requests.session()
			r=s.get(url).text
			rd=r.encode('windows-1251')
			return rd
		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)')
			resp = urllib2.urlopen(req)
			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

def ASE_start():
	srv=__settings__.getSetting("p2p_serv")#'127.0.0.1'
	prt=__settings__.getSetting("p2p_port")#'6878'
	lnk='http://'+srv+':'+prt+'/webui/api/service?method=get_version&format=jsonp&callback=mycallback'#getstream?id='+CID
	pDialog = xbmcgui.DialogProgressBG()
	resp=GET(lnk)
	if resp != '':
		return False
	else:
		#showMessage('Пазл ТВ', 'Запуск Ace Stream')
		pDialog.create('TVFeed', 'Запуск Ace Stream ...')
		pDialog.update(0, message='Запуск Ace Stream ...')
		start_linux()
		start_windows()
		for i in range (0,10):
			pDialog.update(i*10, message='Запуск Ace Stream ...')
			xbmc.sleep(1500)
			resp=GET(lnk)
			if resp != '':
				pDialog.close()
				return True
		pDialog.close()
		return False

def start_linux():
        import subprocess
        try:
            subprocess.Popen(['acestreamengine', '--client-console'])
        except:
            try:
                subprocess.Popen('acestreamengine-client-console')
            except: 
                try:
                    xbmc.executebuiltin('XBMC.StartAndroidActivity("org.acestream.media")')
                    xbmc.sleep(2000)
                    xbmc.executebuiltin('XBMC.StartAndroidActivity("org.xbmc.kodi")')
                except:
                    return False
        return True

def start_windows():
        try:
            import _winreg
            try:
                t = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\AceStream')
            except:
                t = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\TorrentStream')
            path = _winreg.QueryValueEx(t, r'EnginePath')[0]
            os.startfile(path)
            return True
        except:
            return False


import sqlite3 as db
db_name = os.path.join( dbDir, "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.replace('-','').replace('.','')
		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
		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.replace('-','').replace('.','')
		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.replace('-','').replace('.','')
		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
	return Labels


def AddItem(Title = "", mode = "", id='0', url='', total=100):
			if id !='0':
				try:    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]В избранное[/B]', 'Container.Update("plugin://plugin.video.animedia.tv/?mode=Add2List&id='+id+'")'), ('[B]Список раздач[/B]', 'Container.Update("plugin://plugin.video.animedia.tv/?mode=Torrents2&id='+id+'")'), ('[B]Обновить описание[/B]', 'Container.Update("plugin://plugin.video.animedia.tv/?mode=update_info&id='+id+'")')])
			if mode=="OpenTorrent_old":
				try:type=info["type"]
				except:type=''
				if type == '': listitem.addContextMenuItems([('[B]Сохранить сериал[/B]', 'Container.Update("plugin://plugin.video.torrent.checker/?mode=save_episodes_api&url='+urllib.quote_plus(url)+'&name='+urllib.quote_plus(info['originaltitle'])+ '&info=' + urllib.quote_plus(repr(info))+'")'),])
				#else: listitem.addContextMenuItems([('[B]Сохранить фильм(STRM)[/B]', 'Container.Update("plugin://plugin.video.animedia.tv/?mode=Save_strm&id='+id+'&url='+urllib.quote_plus(url)+'")'),])


			if mode=="OpenTorrent":
				le=['ace', 't2http', 'yatp', 'torrenter', 'elementum', 'xbmctorrent', 'ace_proxy', 'quasar', 'torrserver', '']
				tengine = le[int(__settings__.getSetting("Engine"))]

				purl='plugin://plugin.video.tam/?mode=open&url='+urllib.quote_plus(url)+ '&info=' + urllib.quote_plus(repr(info))+ '&engine='+tengine
				listitem.addContextMenuItems([('[B]Сохранить сериал[/B]', 'Container.Update("plugin://plugin.video.tam/?mode=save&url='+urllib.quote_plus(url)+'&purl='+urllib.quote_plus('plugin://plugin.video.anilibria.tv/?mode=Torrents2&id='+id)+ '&info=' + urllib.quote_plus(repr(info))+'")'),])

			if mode=="Wish":
				listitem.addContextMenuItems([('[B]Удалить[/B]', 'Container.Update("plugin://plugin.video.animedia.tv/?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 SrcNavi(md="Navigator", curl=''):
	t=''
	g=''
	y=''
	o=''
	s='entry_date'
	if md =="Navigator":
		Cat    =__settings__.getSetting("Cat")
		Genre  =__settings__.getSetting("Genre")
		Year   =__settings__.getSetting("Year")
		Ongoing=__settings__.getSetting("Ongoing")
		Sort   =__settings__.getSetting("Sort")

		Ongoing=['Любой','Сейчас выходит','Вышедшие']
		Sort=['Популярные','Новые']

		if Cat !='':   t=animedia.type[Cat]
		if Genre !='': g=animedia.genres[Genre]
		if Year !='':  y=animedia.years[Year]
		if Ongoing=='Сейчас выходит': o='0'
		if Ongoing=='Вышедшие':       o='1'
		if Sort=='Новые':      s='entry_date'
		if Sort=='Популярные': s='view_count_one'
		
	elif md=="Popular": 
		s='view_count_one'
	elif md=="New":
		o='0'
	#elif md=="Next":
	#	link=curl
	else:
		L=animedia.search(md)
		md=''
	
	print t,g,y,o,s
	
	if md!='': L=animedia.get_list(t,g,y,o,s)
	
	for info in L:
		id = info['id']
		try:
			try:    info = get_info(id)
			except: pass
			
			rating = info['rating']
			if rating>0: r = str(rating)
			else: r= " - - "
			if len(r)==1: r=r+'.0'
			
			nru = info['title']
			type = ''
			
			AddItem("[ "+r+" ] "+nru+type, "Torrents", id, total=len(L)-2)
		except:
			print 'ошибка получения описания'


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

def du(s):
	return eval('u"'+s.replace('\u','\\u')+'"')

def get_info(ID):
	try:
		info=eval(xt(get_inf_db(ID)))
		cover=unlock(info['cover']+'?h=385&w=280&q=70')
		info['cover']=cover
		#info['funart']=unlock(info['funart'])
		deb_print ('KP get_info ОК')
		return info
	except:
		info = animedia.get_info(ID)
		try:    add_to_db(ID, repr(info))
		except: print "ERR: " + ID
		cover=unlock(info['cover'])
		info['cover']=cover
		#info['funart']=unlock(info['funart'])
		deb_print ('KP return info')
		return info



#==============  Menu  ====================
def Root():
	try:L=eval(__settings__.getSetting("W_list"))
	except: L=[]
	AddItem("Поиск", "Search")
	if __settings__.getSetting("HistoryON") == 'true': AddItem("История", "History")
	AddItem("Каталог", "Navigator")
	AddItem("Популярные", "Popular")
	AddItem("Новые", "New")
	#AddItem("Самые ожидаемые", "Future")
	#AddItem("Списки", "TopLists")
	#AddItem("Персоны", "PersonList")
	if len(L)>0: AddItem("Избранное", "Wish_list")
	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 Navigator():
	Cat    =__settings__.getSetting("Cat")
	Genre  =__settings__.getSetting("Genre")
	Year   =__settings__.getSetting("Year")
	Ongoing=__settings__.getSetting("Ongoing")
	Sort   =__settings__.getSetting("Sort")

	if Cat=="":     Cat=  "--"
	if Genre=="":   Genre="--"
	if Year=="":    Year= "--"
	if Ongoing=="": Ongoing="--"
	if Sort=="": Sort="Популярные"
	
	AddItem("Категория: [COLOR FFFFFF00]" +Cat+    "[/COLOR]",   "SelCat")
	AddItem("Жанр:      [COLOR FFFFFF00]" +Genre+  "[/COLOR]",   "SelGenre")
	AddItem("Год:       [COLOR FFFFFF00]" +Year+   "[/COLOR]",   "SelYear")
	AddItem("Статус:    [COLOR FFFFFF00]" +Ongoing+"[/COLOR]",   "SelOngoing")
	AddItem("Порядок:   [COLOR FFFFFF00]" +Sort+   "[/COLOR]",   "SelSort")
	
	AddItem("[B][COLOR FF00FF00][ Искать ][/COLOR][/B]", "SrcNavi")

def Torrents(id, additm=True):
	info=get_info(id)
	L=animedia.get_torrents(id)
	for i in L:
		if __settings__.getSetting("Magnet")=='false': AddItem(i['title'], "OpenTorrent", id, i['torrent'])
		else:                                          AddItem(i['title'], "OpenTorrent", id, i['magnet'])
	
	return L


def OpenTorrent(url, id):
	#print url
	if 'magnet' in url: return OpenMagnet(url, id)
	
	torrent_data = GETtorr(url)
	if torrent_data != None:
		import bencode
		#torrent = bencode.bdecode(torrent_data)
		try:torrent = bencode.bdecode(torrent_data)
		except: return
		cover = 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.setProperty('IsPlayable', 'true')
				uri = sys.argv[0]+'?mode=PlayTorrent2&id='+id+'&ind='+str(ind)+'&url='+urllib.quote_plus(url)
				xbmcplugin.addDirectoryItem(handle, uri, listitem)
				ind+=1
		except:
				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=PlayTorrent2&id='+id+'&ind='+str(ind)+'&url='+urllib.quote_plus(url)
				xbmcplugin.addDirectoryItem(handle, uri, listitem)

def m2t(m):
	hash=mfind(m+'&', 'btih:', '&')
	url='https://krasfs.ru/download.php?hash='+hash
	t=GET(url)
	if t=='': return ''
	else: return url


def OpenMagnet(url, id):
			cover = icon
			L=list_magnet(url)
			ind=0
			for i in L:
				try: 
					if 'idx=' in url: ind=int(url[url.rfind('idx=')+4:])
				except: pass
				name=i[0]
				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=PlayTorrent2&id='+id+'&ind='+str(ind)+'&url='+urllib.quote_plus(url)
				xbmcplugin.addDirectoryItem(handle, uri, listitem)
				ind+=1


def list_magnet(uri):
		engine=__settings__.getSetting("Engine2")
		if engine=="2": 
			try: return list_ace(uri)
			except: return list_t2h(uri)
		else: return list_t2h(uri)

def list_t2h(uri):
		from contextlib import closing
		sys.path.append(os.path.join(xbmc.translatePath("special://home/"),"addons","script.module.torrent2http","lib"))
		# Create instance of Engine 
		from torrent2http import State, Engine, MediaType
		engine = Engine(uri)
		files = []
		# Ensure we'll close engine on exception 
		progressBar = xbmcgui.DialogProgress()
		progressBar.create('Torrent2Http', 'Запуск')
		with closing(engine):
		# Start engine 
			engine.start()
			# Wait until files received 
			while not files and not xbmc.abortRequested:
				progressBar.update(0, 'Torrent2Http', 'Примагничиваемся', "")
				
				# Will list only video files in torrent
				files = engine.list(media_types=[MediaType.VIDEO])
				# Check if there is loading torrent error and raise exception 
				engine.check_torrent_error()
				xbmc.sleep(200)
				if progressBar.iscanceled() or xbmc.abortRequested:
							progressBar.update(0)
							progressBar.close()
							return []
				
		progressBar.close()
		return files

def list_ace(url):
	progressBar = xbmcgui.DialogProgress()
	progressBar.create('ACE', 'Примагничиваемся')
	srv=__settings__.getSetting("p2p_serv")
	prt=__settings__.getSetting("p2p_port")
	if '&' not in url: url=url+'&'
	CID=mfind(url, 'btih:', '&')
	as_url='http://'+srv+':'+prt+'/ace/getstream?infohash='+CID+"&format=json"#&_idx="+str(0)
	m3u=GET(as_url)
	#print m3u
	if '#EXTINF' not in m3u: 
						progressBar.close()
						if 'failed to load content' in m3u: return [['Ошибка загрузки контента', 0]]
						else: return [['Начать просмотр', 0]]
	L = m3u.splitlines()
	Lt=[]
	Lu=[]
	for e in L:
		if '#EXTINF' in e: Lt.append(e.replace('#EXTINF:-1,',''))
		if 'http:'   in e: Lu.append(e)
	#n=0
	LL=[]
	
	for n in range(0, len(Lu)):
		for i in range(0, len(Lu)):
			u=Lu[i]
			ind=int(u[u.rfind('idx=')+4:])
			if n == ind: LL.append ([Lt[i],ind])
				
	#for k in Lt:
	#	LL.append ([Lt[n], n])
	#	n+=1
	progressBar.close()
	return LL


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 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:
	__settings__.setSetting(id="Cat",     value="")
	__settings__.setSetting(id="Genre",  value="")
	__settings__.setSetting(id="Year",    value="")
	__settings__.setSetting(id="Ongoing", value="")
	__settings__.setSetting(id="Sort",    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 == "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 == "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 == "SrcNavi":
	SrcNavi()
	xbmcplugin.setPluginCategory(handle, PLUGIN_NAME)
	xbmcplugin.endOfDirectory(handle)

if mode == "SelCat":
	sel = xbmcgui.Dialog()
	r = sel.select("Тип:", Cat)
	__settings__.setSetting(id="Cat", value=Cat[r])

if mode == "SelGenre":
	sel = xbmcgui.Dialog()
	r = sel.select("Жанр:", Genre)
	__settings__.setSetting(id="Genre", value=Genre[r])

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

if mode == "SelOngoing":
	sel = xbmcgui.Dialog()
	r = sel.select("Статус:", Ongoing)
	__settings__.setSetting(id="Ongoing", value=Ongoing[r])

if mode == "SelSort":
	sel = xbmcgui.Dialog()
	r = sel.select("Упорядочить:", Sort)
	__settings__.setSetting(id="Sort", value=Sort[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()

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


if mode == "PlayTorrent":
		k_db=chek_in()
		play(url, ind, id)
		if k_db != None: chek_out(k_db)
		xbmc.executebuiltin("Container.Refresh()")

if mode == "PlayTorrent2":
	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 == "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()
