#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#  
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


##############BIBLIOTECAS A IMPORTAR E DEFINICOES####################

import urllib,urllib2,re,xbmcplugin,xbmcgui,xbmc,xbmcaddon,HTMLParser,xmltosrt
from BeautifulSoup import BeautifulSoup
h = HTMLParser.HTMLParser()


versao = '0.0.5'
addon_id = 'plugin.video.ecfilmes'
selfAddon = xbmcaddon.Addon(id=addon_id)
addonfolder = selfAddon.getAddonInfo('path')
artfolder = addonfolder + '/resources/img/'
fanart = addonfolder + '/fanart.jpg'


################################################## 

#MENUS############################################


def CATEGORIES():
	addDir('Categorias','-',1,artfolder + 'categorias.jpg')
	addDir('Últimos Adicionados','http://ecfilmes.com/',2,artfolder + 'ultimos.jpg')
	#addDir('SERIES','http://ecfilmes.com/category/series/',2,artfolder + 'se.jpg')
	addDir('Pesquisar','-',3,artfolder + 'pesquisa.jpg')
	
	

###################################################################################
#FUNCOES
def categorias():
	addDir('1080p','http://ecfilmes.com/category/full-hd-1080p/',2,artfolder + '1080.jpg')
	addDir('720p','http://ecfilmes.com/category/hd-720p/',2,artfolder + '720.jpg')
	addDir('3d','http://ecfilmes.com/category/3d/',2,artfolder + '3.jpg')
	addDir('2013','http://ecfilmes.com/category/2013/',2,artfolder + '13.jpg')
	addDir('2014','http://ecfilmes.com/category/2014',2,artfolder + '14.jpg')
	addDir('Legendados','http://ecfilmes.com/category/legendado/',2,artfolder + 'leg.jpg')
	addDir('Ação','http://ecfilmes.com/category/acao/',2,artfolder + 'ac.jpg')
	addDir('Animação','http://ecfilmes.com/category/animacao/',2,artfolder + 'animacao.jpg')
	addDir('Aventura','http://ecfilmes.com/category/aventura/',2,artfolder + 'aventura.jpg')
	addDir('Comedia','http://ecfilmes.com/category/comedia/',2,artfolder + 'comedia.jpg')
	addDir('Comedia Romantica','http://ecfilmes.com/category/comdia-romantica/',2,artfolder + 'comediaro.jpg')
	addDir('Documentários','http://ecfilmes.com/category/documentarios/',2,artfolder + 'doc.jpg')
	addDir('Drama','http://ecfilmes.com/category/drama/',2,artfolder + 'drama.jpg')
	addDir('Épico','http://ecfilmes.com/category/epico/',2,artfolder + 'ep.jpg')
	addDir('Fantasia','http://ecfilmes.com/category/fantasia/',2,artfolder + 'fan.jpg')
	addDir('Faroeste','http://ecfilmes.com/category/faroeste/',2,artfolder + 'faroeste.jpg')
	addDir('Ficção','http://ecfilmes.com/category/ficcao/',2,artfolder + 'ficcao.jpg')
	addDir('Guerra','http://ecfilmes.com/category/guerra/',2,artfolder + 'gu.jpg')
	addDir('Musical','http://ecfilmes.com/category/musical/',2,artfolder + 'mu.jpg')
	addDir('Policial','http://ecfilmes.com/category/policial/',2,artfolder + 'policial.jpg')
	addDir('Romance','http://ecfilmes.com/category/romance/',2,artfolder + 'romance.jpg')
	addDir('Suspense','http://ecfilmes.com/category/suspense/',2,artfolder + 'suspense.jpg')
	addDir('Terror','http://ecfilmes.com/category/terror/',2,artfolder + 'terror.jpg')
	

def listar_videos(url):
	codigo_fonte = abrir_url(url)
	soup = BeautifulSoup(abrir_url(url))
	try:
		lista_filmes = BeautifulSoup(soup.findAll("ul", { "class" : "lista-filmes" })[3].prettify())
	except:
		lista_filmes = BeautifulSoup(soup.find("ul", { "class" : "lista-filmes" }).prettify())
	capas = lista_filmes.findAll("div", { "class" : "capa" })
	a=[]
	for capa in capas:
		temp = [capa.a["href"],capa.text.encode('ascii', 'ignore'),capa.img["src"]] 
		a.append(temp)
		
	total = len(a)
	for url2, titulo, img in a:
		titulo = titulo.replace('&#8211;',"-").replace('&#8217;',"'")	
		addDir(titulo,url2,4,img,False,total) 
		
		
	page = re.compile("<link rel='next' href='(.+?)' />").findall(codigo_fonte)
	for prox_pagina in page:
		addDir('Página Seguinte >>',prox_pagina,2,artfolder + 'prox.jpg')
		break
	
def obtem_url_google(url):

	html = abrir_url(url)
	FLASHVARS_START = 'flashVars":{'
	start = html.find(FLASHVARS_START) + len(FLASHVARS_START)
	end = html.find('}', start)
	
	flashvars = html[start:end]
	
	d = flashvars.decode('unicode-escape')
	decoded = urllib2.unquote(urllib2.unquote(d))
	#print "ORG Decoded: " + decoded
	
	urls = [l for l in decoded.split('url=') if 'mp4' in l and l.startswith('https')]
	ttsurls = decoded[decoded.find('"ttsurl":"') + len('"ttsurl":"'): decoded.find('",', decoded.find('"ttsurl":"'))] + '&kind&lang=pt-BR&name&type=track'
	ttsurls_id = ttsurls[ttsurls.find('timedtext?id=') + len('timedtext?id='): ttsurls.find('&', ttsurls.find('timedtext?id='))]
	#print "ORG Urls: " + str(urls)
	#print "ORG Ttsurls_id: " + str(ttsurls_id)
	#print "ORG Ttsurls: " + str(ttsurls) + '&v=' + str(ttsurls_id)
	qualidade = []
	url_video = []
	for u in urls:
		itags = {5:'Baixa Qualidade, 240p, FLV, 400x240',
			 17:'Baixa Qualidade, 144p, 3GP, 0x0',
			 18:'Media Qualidade, 480p, MP4, 480x360',
			 59:'Media Qualidade, 360p, MP4, 480x360',
			 22:'Alta Qualidade, 720p, MP4, 1280x720',
			 34:'Media Qualidade, 360p, FLV, 640x360',
			 35:'Standard Definition, 480p, FLV, 854x480',
			 36:'Baixa Qualidade, 240p, 3GP, 0x0',
			 37:'Alta Qualidade, 1080p, MP4, 1920x1080',
			 38:'Original Definition, MP4, 4096x3072',
			 43:'Media Qualidade, 360p, WebM, 640x360',
			 44:'Standard Definition, 480p, WebM, 854x480',
			 45:'Alta Qualidade, 720p, WebM, 1280x720',
			 46:'Alta Qualidade, 1080p, WebM, 1280x720',
			 82:'Media Qualidade 3D, 360p, MP4, 640x360',
			 84:'Alta Qualidade 3D, 720p, MP4, 1280x720',
			 100:'Media Qualidade 3D, 360p, WebM, 640x360',
			 102:'Alta Qualidade 3D, 720p, WebM, 1280x720'}
		q = 'quality='
		i = 'itag='
		quality = u[u.find(q) + len(q): u.find(',', u.find(q))]
		itag = u[u.find(i) + len(i): u.find('&', u.find(i))]
		#print "ORG qualitys: " + quality
		#print "ORG itag: " + itag
		try:
			quality = itags[int(itag)]
		except:
			pass
		qualidade.append(quality)
		url_video.append(u[:-1])
	index = xbmcgui.Dialog().select('Qualidade do vídeo:', qualidade)
	if index == -1: return['-','-'] # Tive que alterar esta linha para corrigir um pequeno erro
	return [url_video[index],str(ttsurls) + '&v=' + str(ttsurls_id)]

def player(name,url,iconimage):
	google = r'src="(.*?google.*?/preview)"'
	picasa = r'src="(.*?filmesonlinebr.*?/player/.*?)"'
	vk = r'src="(.*?vk.*?/video.*?)"'
	nvideo = r'src="(.*?nowvideo.*?/embed.*?)"'
	dropvideo = r'src="(.*?dropvideo.*?/embed.*?)"'
	vodlocker = r'src="(.*?vodlocker.*?/embed.*?)"'
	dropmega = r'src=".*?dropmega.*?id=(.*?)"'
	
	mensagemprogresso = xbmcgui.DialogProgress()
	mensagemprogresso.create('EcFilmes', 'A resolver link','Por favor aguarde...')
	mensagemprogresso.update(33)
	
	links = []
	hosts = []
	matriz = []
	codigo_fonte = abrir_url(url)
	
	try:
		links.append(re.findall(picasa, codigo_fonte)[0])
		hosts.append('Picasa')
	except:
		pass
	
	try:
		links.append(re.findall(google, codigo_fonte)[0])
		hosts.append('Gdrive')
	except:
		pass
	
	try:
		links.append(re.findall(vk, codigo_fonte)[0])
		hosts.append('Vk')
	except:
		pass
	
	try:
		links.append(re.findall(nvideo, codigo_fonte)[0])
		hosts.append('Nowvideo - Sem suporte')
	except:
		pass
	
	try:
		links.append(re.findall(dropvideo, codigo_fonte)[0])
		hosts.append('Dropvideo')
	except:
		pass
	
	try:
		links.append('http://www.dropvideo.com/embed/'+re.findall(dropmega, codigo_fonte)[0])
		hosts.append('Dropvideo')
	except:
		pass
	
	try:
		links.append(re.findall(vodlocker, codigo_fonte)[0])
		hosts.append('Vodlocker - Sem suporte')
	except:
		pass
	
	if not hosts:
		return
	
	index = xbmcgui.Dialog().select('Selecione um dos hosts suportados :', hosts)
	
	if index == -1:
		return

	url_video = links[index]
	mensagemprogresso.update(66)
	
	print 'Player url: %s' % url_video
	if 'google' in url_video:
		matriz = obtem_url_google(url_video)
	elif 'dropvideo.com/embed' in url_video:
		matriz = obtem_url_dropvideo(url_video)   # esta linha está a mais
	elif 'filmesonlinebr.info/player' in url_video:
		matriz = obtem_url_picasa(url_video)
	elif 'vk.com/video_ext' in url_video:
		matriz = obtem_url_vk(url_video)
	else:
		print "Falha: " + str(url_video)
	print matriz
	url = matriz[0]
	print url
	if url=='-': return
	legendas = matriz[1]
	print "Url do gdrive: " + str(url_video)
	print "Legendas: " + str(legendas)
	
	mensagemprogresso.update(100)
	mensagemprogresso.close()
	
	listitem = xbmcgui.ListItem() # name, iconImage="DefaultVideo.png", thumbnailImage="DefaultVideo.png"
	listitem.setPath(url)
	listitem.setProperty('mimetype','video/mp4')
	listitem.setProperty('IsPlayable', 'true')
	#try:
	xbmcPlayer = xbmc.Player(xbmc.PLAYER_CORE_AUTO)
	xbmcPlayer.play(url)
	if legendas != '-':
		if 'timedtext' in legendas:
			#legenda = xmltosrt.convert(legendas)
			#try:
				import os.path
				sfile = os.path.join(xbmc.translatePath("special://temp"),'sub.srt')
				sfile_xml = os.path.join(xbmc.translatePath("special://temp"),'sub.xml')#timedtext
				sub_file_xml = open(sfile_xml,'w')
				sub_file_xml.write(urllib2.urlopen(legendas).read())
				sub_file_xml.close()
				print "Sfile.srt : " + sfile_xml
				xmltosrt.main(sfile_xml)
				xbmcPlayer.setSubtitles(sfile)
			#except:
			#	pass
		else:
			xbmcPlayer.setSubtitles(legendas)
	
def pesquisa():
	keyb = xbmc.Keyboard('', 'faca a procura') #Chama o keyboard do XBMC com a frase indicada
	keyb.doModal() #Espera ate que seja confirmada uma determinada string
	if (keyb.isConfirmed()): #Se a entrada estiver confirmada (isto e, se carregar no OK)
		search = keyb.getText() #Variavel search fica definida com o conteudo do formulario
		parametro_pesquisa=urllib.quote(search) #parametro_pesquisa faz o quote da expressao search, isto Ã©, escapa os parametros necessarios para ser incorporado num endereÃ§o url
		url = 'http://ecfilmes.com/?s=%s&tipo=video' % str(parametro_pesquisa) #nova definicao de url. str forÃ§a o parametro de pesquisa a ser uma string
		listar_videos(url) #chama a funÃ§Ã£o listar_videos com o url definido em cima

		###################################################################################

'''def addDirPlayer(name,url,mode,iconimage,total):
	# plot é a sinopse do filme... da maneira que está definido não apanha sinopses. (nota: não sei se o site tem sinopses. Se não tiver, este codigo é desnecessario)
	# Isto estava lento porque esta função estava a pesquisar por sinopses mas nunca encontrava
	codigo_fonte = abrir_url(url)
	try: plot = re.compile('<meta name="description" content="(.+?)" />').findall(codigo_fonte)[0]
	except: plot = 'Erro a obter sinopse...'
	
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setProperty('fanart_image', fanart)
	liz.setInfo( type="Video", infoLabels= { "Title": name,
											 "OriginalTitle": name,
											 "Plot": plot 
											 } )
	cm = []
	cm.append(('Sinopse', 'XBMC.Action(Info)'))
	liz.addContextMenuItems(cm, replaceItems=True)
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False,totalItems = total)
	return ok'''

def abrir_url(url):
	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()
	return link

def addLink(name,url,iconimage):
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
	liz.setProperty('fanart_image', fanart)
	liz.setInfo( type="Video", infoLabels={ "Title": name } )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
	return ok

def addDir(name,url,mode,iconimage,pasta=True,total=1):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setProperty('fanart_image', fanart)
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=pasta,totalItems=total)
	return ok

############################################################################################################
#                                               GET PARAMS                                                 #
############################################################################################################
              
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

      
params=get_params()
url=None
name=None
mode=None
iconimage=None


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

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


print "Mode: "+str(mode)
print "URL: "+str(url)
print "Name: "+str(name)
print "Iconimage: "+str(iconimage)




###############################################################################################################
#                                                   MODOS                                                     #
###############################################################################################################


if mode==None or url==None or len(url)<1:
        print ""
        CATEGORIES()

elif mode==1:
	print ""
	categorias()
	
elif mode==2:
	print ""
	listar_videos(url)
	
elif mode==3:
	print ""
	pesquisa()

elif mode==4:
	print ""
	player(name,url,iconimage)
	
elif mode==5:
	print ""
	listar_videos_M18(url)
	
xbmcplugin.endOfDirectory(int(sys.argv[1]))