#!/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
from BeautifulSoup import BeautifulSoup
from tools import *
h = HTMLParser.HTMLParser()


versao = '0.0.5'
addon_id = 'plugin.video.filmesonlinegratis'
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://www.filmesonlinegratis.net/',2,artfolder + '20.jpg')
	addDir('Series','http://www.filmesonlinegratis.net/series',2,artfolder + 'series.jpg')
	addDir('Pesquisar','-',3,artfolder + '21.jpg')
	xbmcplugin.setContent(int(sys.argv[1]), 'movies')
	xbmc.executebuiltin('Container.SetViewMode(500)')
	

###################################################################################
#FUNCOES
def categorias():
	addDir('Ação','http://www.filmesonlinegratis.net/acao',2,artfolder + '1.jpg')
	addDir('Animação','http://www.filmesonlinegratis.net/animacao',2,artfolder + '2.jpg')
	addDir('Aventura','http://www.filmesonlinegratis.net/aventura',2,artfolder + '3.jpg')
	addDir('Comedia','http://www.filmesonlinegratis.net/comedia',2,artfolder + '4.jpg')
	addDir('Comedia Romantica','http://www.filmesonlinegratis.net/comedia-romantica',2,artfolder + '5.jpg')
	addDir('Crime','http://www.filmesonlinegratis.net/crime',2,artfolder + '6.jpg')
	addDir('Documentários','http://www.filmesonlinegratis.net/documentario',2,artfolder + '7.jpg')
	addDir('Drama','http://www.filmesonlinegratis.net/drama',2,artfolder + '8.jpg')
	addDir('Faroeste','http://www.filmesonlinegratis.net/faroeste',2,artfolder + '9.jpg')
	addDir('Ficção','http://www.filmesonlinegratis.net/ficcao-cientifica',2,artfolder + '10.jpg')
	addDir('Guerra','http://www.filmesonlinegratis.net/guerra',2,artfolder + '11.jpg')
	addDir('Musical','http://www.filmesonlinegratis.net/musical',2,artfolder + '12.jpg')
	addDir('Policial','http://www.filmesonlinegratis.net/policial',2,artfolder + '13.jpg')
	addDir('Romance','http://www.filmesonlinegratis.net/romance',2,artfolder + '14.jpg')
	addDir('Suspense','http://www.filmesonlinegratis.net/suspense',2,artfolder + '15.jpg')
	#addDir('Series','http://www.filmesonlinegratis.net/series',2,artfolder + 'series.jpg')
	addDir('Terror','http://www.filmesonlinegratis.net/terror',2,artfolder + '16.jpg')
	addDir('Thriller','http://www.filmesonlinegratis.net/thriller',2,artfolder + '17.jpg')
        
def listar_videos(url):
	codigo_fonte = abrir_url(url)
	soup = BeautifulSoup(abrir_url(url))
##	ow = open('C:\\Python27\\smartflix.html','w')
##	ow.write(codigo_fonte)
##	ow.close()
	lista_filmes = BeautifulSoup(soup.find("div", { "class" : "miniaturas" }).prettify())
	filmes = lista_filmes.findAll("article", { "class" : "miniatura" })
	a=[]
	for filme in filmes:
		print 'Divs: \n' + str(filme('div'))
		plot = ''
		for div in filme('div'):
			if 'Sinopse' in div.text:
				plot = div.text
				break
		if not plot:
			plot = filme('span')[1].text
		temp = [filme('div')[0].a["href"],html_replace_clean(filme('img')[0]["alt"].encode('ascii', 'xmlcharrefreplace')),filme('img')[0]["src"],html_replace_clean(plot.encode('ascii', 'xmlcharrefreplace'))] 
		a.append(temp)
	print plot.encode('ascii', 'xmlcharrefreplace')
	total = len(a)
	for url2, titulo, img, plot in a:
		titulo = titulo.replace('&#8211;',"-").replace('&#8217;',"'")	
		addDir(titulo,url2,4,img,False,total,plot)
		
	p_page = soup.find('a',{'class':'blog-pager-older-link'})
	if p_page:
		addDir('Página Seguinte >>',p_page['href'],2,artfolder + 'prox.jpg')
	
	xbmcplugin.setContent(int(sys.argv[1]), 'movies')
	xbmc.executebuiltin('Container.SetViewMode(503)')

def obtem_url_dropvideo(url):
	codigo_fonte = abrir_url(url)
	try:
		if not 'dropvideo.com/embed/' in url:
			id_video = re.findall(r'<iframe src="http://www.dropvideo.com/embed/(.*?)/"',codigo_fonte)[0]
			codigo_fonte = abrir_url('http://www.dropvideo.com/embed/%s/' % id_video)
			url_video = re.findall(r'var vurl2 = "(.*?)";',codigo_fonte)[0]
			url_legendas =	re.compile('var vsubtitle = "(.*?)";').findall(codigo_fonte)[0]
		else:
			codigo_fonte = abrir_url(url)
			url_video = re.findall(r'var vurl2 = "(.*?)";',codigo_fonte)[0]
			url_legendas =	re.compile('var vsubtitle = "(.*?)";').findall(codigo_fonte)[0]
	except:
		url_video = '-'
		url_legendas = '-'
	return [url_video,url_legendas]


def obtem_url_vk(url):
	codigo_fonte = abrir_url(url)
	qualidade = []
	urls = []
	try:
		urls_video = re.findall(r'url([0-9]+)=(.*?)&', codigo_fonte)
		for qualidade_ , url_ in urls_video:
			qualidade_ = qualidade_+"p"
			if not qualidade_ in qualidade:
				qualidade.append(qualidade_)
			if not url_ in urls:
				urls.append(url_)
		index = xbmcgui.Dialog().select('Qualidade do vídeo:', qualidade)
		return [urls[index],"-"]
	except:
		return ["-","-"]

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 obtem_url_firedrive(url):
	import mechanize, cookielib
	
	br = mechanize.Browser()

	cj = cookielib.LWPCookieJar()
	br.set_cookiejar(cj)
	
	br.set_handle_equiv(True)
	br.set_handle_gzip(True)
	br.set_handle_redirect(True)
	br.set_handle_referer(True)
	br.set_handle_robots(False)
	
	br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
	
	br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1'),("Referer","http://www.firedrive.com")]
	br.open(url)
	br.select_form(nr=0)
	response1 = br.submit()
	html = response1.read()
	
	video_url = re.findall(r"file:.'(.*?)',",html)[0]
	return [video_url,"-"]


def player(name,url,iconimage):
	google = r'src="(.*?google.*?/preview)"'
	picasa = r'src="(.*?filmesonlinebr.*?/player/.*?)"'
	vk = r'<iframe data-src="(.*?vk.*?)" width="538" height="408" frameborder="0">'
	nvideo = r'src="(.*?nowvideo.*?/embed.*?)"'
	dropvideo = r'http://dropvideo.com/embed/(.*?)/'
	vodlocker = r'src="(.*?vodlocker.*?/embed.*?)"'
	dropmega = r'src=".*?dropmega.*?id=(.*?)"'
	firedrive = r"https://www.firedrive.com/embed/(.*?)'"
	
	mensagemprogresso = xbmcgui.DialogProgress()
	mensagemprogresso.create('Smartflix', 'A resolver link','Por favor aguarde...')
	mensagemprogresso.update(33)
	
	links = []
	hosts = []
	matriz = []
	codigo_fonte = abrir_url(url)
	
	try:
		links.append("https://www.firedrive.com/embed/"+re.findall(firedrive, codigo_fonte)[0])
		hosts.append('Firedrive')
	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("http://dropvideo.com/embed/"+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)
	elif 'firedrive.com/embed' in url_video:
		matriz = obtem_url_firedrive(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=iconimage, thumbnailImage=iconimage)
	listitem.setThumbnailImage(iconimage)
	listitem.setProperty('mimetype','video/mp4')
	listitem.setInfo('video', {'Title': name})
	xbmc.Player( xbmc.PLAYER_CORE_MPLAYER ).play(url, listitem)
	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://smartflixfilmeshd.blogspot.com.br/search?' % 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

def addDir(name,url,mode,iconimage,pasta=True,total=1,plot=''):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setProperty('fanart_image', fanart)
	liz.setInfo( type="video", infoLabels={ "title": name, "plot": plot } )
	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]))
