def get_online_list(): logger.info("simpletv.get_online_list") # Login try: request_headers = [] request_headers.append(["User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0"]) post = urllib.urlencode({'log':config.get_setting("simpletvuser"), 'pwd':config.get_setting("simpletvpassword"), 'rememberme':'forever', 'wp-submit':'Acceder', 'redirect_to':'http://web.iptvonline.com.es/wp-admin/', 'testcookie':'1' }) data = scrapertools.cache_page("http://web.iptvonline.com.es/wp-login.php", headers=request_headers, post=post) # Página con la lista request_headers = [] request_headers.append(["User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0"]) request_headers.append(["Referer","http://web.iptvonline.com.es/playlist-simpletv"]) data = scrapertools.cache_page("http://temp.iptvonline.com.es", headers=request_headers) logger.info("data="+data) # Averigua la URL de la lista url = scrapertools.get_match(data,'URL PARA ACTUALIZAR\: (http.*?m3u)') # Descarga la lista data = scrapertools.cache_page(url) except: data = "" return data
def mainlist(item): logger.info("[descargas.py] mainlist") itemlist = [] # Lee la ruta de descargas downloadpath = config.get_setting("downloadpath") logger.info("[descargas.py] downloadpath=" + downloadpath) itemlist.append(Item(channel="descargas", action="pendientes", title="Descargas pendientes")) itemlist.append(Item(channel="descargas", action="errores", title="Descargas con error")) # Añade al listado de XBMC try: ficheros = os.listdir(downloadpath) for fichero in ficheros: logger.info("[descargas.py] fichero=" + fichero) if fichero != "lista" and fichero != "error" and fichero != ".DS_Store" and not fichero.endswith(".nfo") \ and not fichero.endswith(".tbn") \ and os.path.join(downloadpath, fichero) != config.get_setting("downloadlistpath"): url = os.path.join(downloadpath, fichero) if not os.path.isdir(url): itemlist.append(Item(channel="descargas", action="play", title=fichero, fulltitle=fichero, url=url, server="local", folder=False)) except: logger.info("[descargas.py] exception on mainlist") pass return itemlist
def check_video_options(item, video_urls): itemlist = [] #Opciones Reproducir playable = (len(video_urls) > 0) for video_url in video_urls: itemlist.append(item.clone(option=config.get_localized_string(30151) + " " + video_url[0], video_url= video_url[1], action="play_video")) if item.server=="local": itemlist.append(item.clone(option=config.get_localized_string(30164), action="delete_file")) if not item.server=="local" and playable: itemlist.append(item.clone(option=config.get_localized_string(30153), action="download", video_urls = video_urls)) if item.channel=="favoritos": itemlist.append(item.clone(option=config.get_localized_string(30154), action="remove_from_favorites")) if not item.channel=="favoritos" and playable: itemlist.append(item.clone(option=config.get_localized_string(30155), action="add_to_favorites", item_action = item.action)) if not item.strmfile and playable and item.contentType == "movie": itemlist.append(item.clone(option=config.get_localized_string(30161), action="add_to_library", item_action = item.action)) if config.get_setting("jdownloader_enabled")=="true" and playable: itemlist.append(item.clone(option=config.get_localized_string(30158), action="send_to_jdownloader")) if config.get_setting("pyload_enabled")=="true" and playable: itemlist.append(item.clone(option=config.get_localized_string(30158).replace("jdownloader","pyLoad"), action="send_to_pyload")) if not item.channel in ["Trailer","ecarteleratrailers"] and playable: itemlist.append(item.clone(option=config.get_localized_string(30162), action="search_trailer")) return itemlist
def get_list_canales(): logger.info("streamondemand.channels.novedades get_list_canales") list_canales = {'peliculas': [], 'infantiles': [], 'series': [], 'anime': [], 'documentales': []} # Rellenar listas de canales disponibles channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml') channel_language = config.get_setting("channel_language") if channel_language == "": channel_language = "all" for infile in sorted(glob.glob(channels_path)): list_result_canal = [] channel_id = os.path.basename(infile)[:-4] channel_parameters = channeltools.get_channel_parameters(channel_id) # No incluir si es un canal inactivo if channel_parameters["active"] != "true": continue # No incluir si es un canal para adultos, y el modo adulto está desactivado if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "false": continue # No incluir si el canal es en un idioma filtrado if channel_language != "all" and channel_parameters["language"] != channel_language: continue # Incluir en cada categoria, si en su configuracion el canal esta activado para mostrar novedades for categoria in list_canales: include_in_newest = config.get_setting("include_in_newest_" + categoria, channel_id) if include_in_newest: channels_ID_name[channel_id] = channel_parameters["title"] list_canales[categoria].append((channel_id,channel_parameters["title"])) return list_canales
def start(thread = True): if thread: t = threading.Thread(target=start, args=[False]) t.setDaemon(True) t.start() else: import time updatelibrary_wait = [0, 10000, 20000, 30000, 60000] wait = updatelibrary_wait[int(config.get_setting("updatelibrary_wait", "biblioteca"))] if wait > 0: time.sleep(wait) # Comprobar version de la bilbioteca y actualizar si es necesario if config.get_setting("library_version") != 'v4': platformtools.dialog_ok(config.PLUGIN_NAME.capitalize(), "Se va a actualizar la biblioteca al nuevo formato", "Seleccione el nombre correcto de cada serie o película, si no está seguro pulse 'Cancelar'.") if not convert_old_to_v4(): platformtools.dialog_ok(config.PLUGIN_NAME.capitalize(), "ERROR, al actualizar la biblioteca al nuevo formato") else: # La opcion 2 es "Una sola vez al dia" if not config.get_setting("updatelibrary", "biblioteca") == 2: check_for_update(overwrite=False) else: if not config.get_setting("updatelibrary", "biblioteca") == 2: check_for_update(overwrite=False) # Se ejecuta ciclicamente while True: monitor_update() time.sleep(3600) # cada hora
def login(check_login=True): logger.info() try: user = config.get_setting("verseriesynovelasuser", "verseriesynovelas") password = config.get_setting("verseriesynovelaspassword", "verseriesynovelas") if user == "" and password == "": return False, "Para ver los enlaces de este canal es necesario registrarse en www.verseriesynovelas.tv" elif user == "" or password == "": return False, "Usuario o contraseña en blanco. Revisa tus credenciales" if check_login: data = httptools.downloadpage("http://www.verseriesynovelas.tv/").data if user in data: return True, "" post = "log=%s&pwd=%s&redirect_to=http://www.verseriesynovelas.tv/wp-admin/&action=login" % (user, password) data = httptools.downloadpage("http://www.verseriesynovelas.tv/iniciar-sesion", post=post).data if "La contraseña que has introducido" in data: logger.info("pelisalacarta.channels.verseriesynovelas Error en el login") return False, "Contraseña errónea. Comprueba tus credenciales" elif "Nombre de usuario no válido" in data: logger.info("pelisalacarta.channels.verseriesynovelas Error en el login") return False, "Nombre de usuario no válido. Comprueba tus credenciales" else: logger.info("pelisalacarta.channels.verseriesynovelas Login correcto") return True, "" except: import traceback logger.info(traceback.format_exc()) return False, "Error durante el login. Comprueba tus credenciales"
def yearsearch(item): user_id = config.get_setting("stormtvuser") user_pass = config.get_setting("stormtvpassword") path = config.get_data_path() + "stormtv/temp/" urllib.urlretrieve(SERVER + "tvseries/years", path + "temp.xml") xml = path + "/" + "temp.xml" doc = minidom.parse(xml) node = doc.documentElement years = doc.getElementsByTagName("year") if DEBUG: print len(years) itemlist = [] for year in years: name = year.getElementsByTagName("name")[0].childNodes[0].data if DEBUG: logger.info("[stormtv.py] yearsearch ###" + name + "$$") id = year.getElementsByTagName("id")[0].childNodes[0].data itemlist.append( Item( channel=__channel__, action="yeartvs", title=name, fulltitle=name, url=id, thumbnail=SERVER + "logo.jpg", plot="", viewmode="movie_with_plot", show=id, fanart=SERVER + "logo.jpg", ) ) return itemlist
def start(): logger.info("pelisalacarta server init...") config.verify_directories_created() try: HTTPServer.start(MostrarInfo) WebSocket.start(MostrarInfo) # Da por levantado el servicio logger.info("--------------------------------------------------------------------") logger.info("Pelisalacarta Iniciado") logger.info("La URL para acceder es http://" + myip + ":" + str(http_port)) logger.info("WebSocket Server iniciado en ws://" + myip + ":" + str(websocket_port)) logger.info("--------------------------------------------------------------------") logger.info("Runtime Path : " + config.get_runtime_path()) logger.info("Data Path : " + config.get_data_path()) logger.info("Download Path : " + config.get_setting("downloadpath")) logger.info("DownloadList Path : " + config.get_setting("downloadlistpath")) logger.info("Bookmark Path : " + config.get_setting("bookmarkpath")) logger.info("Library Path : " + config.get_setting("librarypath")) logger.info("--------------------------------------------------------------------") MostrarInfo() start = True while start: time.sleep(1) except KeyboardInterrupt: print 'Deteniendo el servidor HTTP...' HTTPServer.stop() print 'Deteniendo el servidor WebSocket...' WebSocket.stop() print 'Pelisalacarta Detenido' start = False
def getmainlist(preferred_thumb=""): logger.info("channelselector.getmainlist") itemlist = [] if config.get_setting("programs_enable_section")=="true": if config.get_setting("programs_enable_subsections")!="true": itemlist.append( Item(title="Programas" , channel="api_programas" , action="mainlist", thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),"menu/updated.png")) ) else: itemlist.append( Item(title="Programas" , channel="api_programas" , action="programas", thumbnail=api.get_section_thumbnail("programas")) ) itemlist.append( Item(title="Informativos" , channel="api_programas" , action="informativos", thumbnail=api.get_section_thumbnail("informativos")) ) itemlist.append( Item(title="Deportes" , channel="api_programas" , action="deportes", thumbnail=api.get_section_thumbnail("deportes")) ) itemlist.append( Item(title="Series" , channel="api_programas" , action="series", thumbnail=api.get_section_thumbnail("series")) ) itemlist.append( Item(title="Infantil" , channel="api_programas" , action="infantil", thumbnail=api.get_section_thumbnail("infantil")) ) itemlist.append( Item(title="Cine" , channel="api_programas" , action="cine", thumbnail=api.get_section_thumbnail("cine")) ) itemlist.append( Item(title="Canales" , channel="channelselector" , action="channeltypes", thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),"menu/channels.png")) ) itemlist.append( Item(title="Directos" , channel="directos" , action="mainlist", thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),"menu/live.png")) ) #itemlist.append( Item(title="Buscador" , channel="buscador" , action="mainlist" , thumbnail = urlparse.urljoin(get_thumbnail_path(preferred_thumb),"menu/search.png")) ) itemlist.append( Item(title="Descargas" , channel="descargas" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(preferred_thumb),"menu/downloads.png")) ) itemlist.append( Item(title="Favoritos" , channel="favoritos" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(preferred_thumb),"menu/favorites.png")) ) itemlist.append( Item(title="Configuración" , channel="configuracion" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(preferred_thumb),"menu/settings.png")) ) itemlist.append( Item(title="Ayuda" , channel="ayuda" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(preferred_thumb),"menu/help.png")) ) return itemlist
def getpreferences(): print "[stormlib.py] getpreferences " user_id = config.get_setting("stormtvuser") user_pass = config.get_setting("stormtvpassword") # server= "https://"+__server__+"/stormtv_v2/public/" # path=config.get_data_path()+"stormtv_v2/temp/" if not os.path.exists(PATH): print "Creating data_path " + PATH try: mkdir_p(PATH) except: pass urllib.urlretrieve( SERVER + "followers/preferences/user/" + user_id + "/pass/" + user_pass, PATH + "preferences.xml" ) # comprobar si hay error de usuario xml = PATH + "preferences.xml" if not os.path.exists(xml): status = "1" print "[stormlib.py] getpreferences " + status else: doc = minidom.parse(xml) node = doc.documentElement error = doc.getElementsByTagName("error") if len(error) > 0: status = "1" print "[stormlib.py] getpreferences " + status else: status = "0" print "[stormlib.py] getpreferences " + status return status
def ItemInfo(parent, item, windowmode): item.title = unicode(item.title,"utf-8","ignore").encode("utf8") item.fulltitle = unicode(item.fulltitle,"utf-8","ignore").encode("utf8") item.plot = unicode(item.plot,"utf-8","ignore").encode("utf8") titulo = item.title import time if item.duration: if item.duration > 3599: Tiempo = time.strftime("%H:%M:%S", time.gmtime(item.duration)) else: Tiempo= time.strftime("%M:%S", time.gmtime(item.duration)) if item.action <> "mainlist": if config.get_setting("duracionentitulo")=="true" and item.duration: titulo = titulo + " [COLOR gold](" + Tiempo + ")[/COLOR]" if config.get_setting("calidadentitulo")=="true" and item.quality: titulo = titulo + " [COLOR orange][" + item.quality + "][/COLOR]" if config.get_setting("idiomaentitulo")=="true" and item.language: titulo = titulo + " [COLOR green][" + item.language + "][/COLOR]" #Si el item tiene fulltitle este manda sobre lo anterior, se mostrara este. if item.fulltitle: titulo=item.fulltitle thumbnail = item.thumbnail if thumbnail == "" and item.folder == True: thumbnail = "%s/thumb_folder.png" if thumbnail == "" and item.folder == False: thumbnail = "%s/thumb_nofolder.png" if windowmode == 2: if "%sthumb_atras.png" in thumbnail: thumbnail = thumbnail %(os.path.join(config.get_runtime_path(), 'resources', "images","icon_")) if "%s" in thumbnail: thumbnail = thumbnail %(config.get_thumbnail_path("")) else: if "%sthumb_atras.png" in thumbnail: thumbnail = thumbnail %(os.path.join(config.get_runtime_path(), 'resources', "images","")) if "%s" in thumbnail: thumbnail = thumbnail %(config.get_thumbnail_path("bannermenu")) return item, titulo, thumbnail
def getplayByID(item): logger.info("[justintv.py] plyByID") tecleado = "" default = "" itemlist = [] tecleado = teclado(heading=config.get_localized_string(30405)) if len(tecleado)>0: item.url = 'http://api.justin.tv/api/stream/list.json?channel='+tecleado itemlist = getlistchannel(item) if len(itemlist)>0: if config.get_setting('streamlive') == 'true': xbmctools.renderItems(itemlist, [], '', 'Movies',isPlayable='true') else: return itemlist elif config.get_setting('streamlive') != 'true': xbmc.executebuiltin("XBMC.Notification(Justin tv,Streaming no encontrado... verificando archivos"+",5000,"+jtv_icon+")") item.url = tecleado item.action = 'getplayByID' itemlist = listarchives(item) if itemlist is not None and len(itemlist)>0: return itemlist else: channelANDarchivesEmpty() else: channelEmpty() return
def channels_list(): itemlist = [] itemlist.append( Item( viewmode="movie", title="Tengo una URL" , channel="tengourl" , language="" , category="F,S,D,A" , type="generic" )) if config.get_setting("personalchannel")=="true": itemlist.append( Item( title=config.get_setting("personalchannelname") , channel="personal" , language="" , category="F,S,D,A" , type="generic" )) if config.get_setting("personalchannel2")=="true": itemlist.append( Item( title=config.get_setting("personalchannelname2") , channel="personal2" , language="" , category="F,S,D,A" , type="generic" )) if config.get_setting("personalchannel3")=="true": itemlist.append( Item( title=config.get_setting("personalchannelname3") , channel="personal3" , language="" , category="F,S,D,A" , type="generic" )) if config.get_setting("personalchannel4")=="true": itemlist.append( Item( title=config.get_setting("personalchannelname4") , channel="personal4" , language="" , category="F,S,D,A" , type="generic" )) if config.get_setting("personalchannel5")=="true": itemlist.append( Item( title=config.get_setting("personalchannelname5") , channel="personal5" , language="" , category="F,S,D,A" , type="generic" )) itemlist.append( Item( title="Cineblog01 (IT)" , channel="cineblog01" , language="IT" , category="F,S,A,VOS" , type="generic" )) itemlist.append( Item( title="Film per tutti (IT)" , channel="filmpertutti" , language="IT" , category="F,S,A" , type="generic" )) itemlist.append( Item( title="Film Senza Limiti (IT)" , channel="filmsenzalimiti" , language="IT" , category="F" , type="generic" )) itemlist.append( Item( title="ItaliaFilms.tv (IT)" , channel="italiafilm" , language="IT" , category="F,S,A" , type="generic" )) itemlist.append( Item( title="Itastreaming (IT)" , channel="itastreaming" , language="IT" , category="F,S,A" , type="generic" )) itemlist.append( Item( title="Pirate Streaming (IT)" , channel="piratestreaming" , language="IT" , category="F" , type="generic" )) # jesus 16/7/2012 itemlist.append( Item( title="Robinfilm (IT)" , channel="robinfilm" , language="IT" , category="F" , type="generic" )) # jesus 16/05/2011 itemlist.append( Item( title="Serie TV Sub ITA" , channel="serietvsubita" , language="IT" , category="S" , type="generic" , extra="Series" )) itemlist.append( Item( title="Griffin Ita" , channel="griffin" , language="IT" , category="F,S,D,A" , type="generic" )) itemlist.append( Item( title="Itastreaming_test" , channel="itastreaming_test" , language="IT" , category="F,S,D,A" , type="generic" )) itemlist.append( Item( title="Guardare Film (IT)" , channel="guardarefilm" , language="IT" , category="F,S,D,A" , type="generic" )) return itemlist
def generate_usertoken(auth_token): LOGIN = config.get_setting("serieslyuser") PASSWORD = config.get_setting("serieslypassword") url = "http://api.series.ly/v2/user/user_token" post = "auth_token=%s&username=%s&password=%s&remember=1&user_agent=''" % ( auth_token, qstr(LOGIN), qstr(PASSWORD) ) data = scrapertools.cache_page(url,post=post) logger.info("****") logger.info(data) logger.info("****") user_data=load_json(data) if "error" in user_data: if user_data["error"]!=0: error_message(user_data["error"]) return False else: return False path=config.get_data_path() logger.info(path) f =open(path+"seriesly_auth", "a") f.write(str(data)) logger.info(str(data)) f.close() user_token=user_data["user_token"] return user_token
def buscar(Globalitemlist,modulo, texto): import threading import urlparse import time Inicio = time.time() Threads[threading.current_thread().name] = {"Canal":modulo.channel,"Inicio": Inicio,"Tiempo":None} ListaCanales = [] try: exec "from channels import "+modulo.channel+" as channel" mainlist_itemlist = channel.mainlist(Item()) for item in mainlist_itemlist: if item.action =="search": url = item.url itemlist = [] itemlist.extend(channel.search(item, texto)) if config.get_setting("buscador_resultados") =="1": if len(itemlist)>0: cantidad = str(len(itemlist)) if len(itemlist) >1: if itemlist[len(itemlist)-1].action <> itemlist[len(itemlist)-2].action: cantidad = str(len(itemlist)) + "+" ListaCanales.append( Item(channel=__channel__ , thumbnail=urlparse.urljoin(config.get_thumbnail_path(),modulo.channel+".png"),action='buscar_canal', url=modulo.channel +"{}"+ url +"{}"+ texto, title=modulo.title + " (" + cantidad + ")" )) else: if len(itemlist) >1: if itemlist[len(itemlist)-1].action <> itemlist[len(itemlist)-2].action: itemlist.remove(itemlist[len(itemlist)-1]) ListaCanales.extend(itemlist) except: logger.info("No se puede buscar en: "+ modulo.channel) Globalitemlist.extend( ListaCanales) if config.get_setting("buscador_multithread") =="1": Threads[threading.current_thread().name]["Tiempo"]=time.time()-Inicio
def mainlist(params, url, category): logger.info("channelselector.mainlist") # Verifica actualizaciones solo en el primer nivel if config.get_platform() != "boxee": try: from core import updater except ImportError: logger.info("channelselector.mainlist No disponible modulo actualizaciones") else: if config.get_setting("updatecheck2") == "true": logger.info("channelselector.mainlist Verificar actualizaciones activado") updater.checkforupdates() else: logger.info("channelselector.mainlist Verificar actualizaciones desactivado") itemlist = getmainlist() for elemento in itemlist: logger.info("channelselector item=" + elemento.title) addfolder( elemento.title, elemento.channel, elemento.action, thumbnailname=elemento.thumbnail, folder=elemento.folder ) # Label (top-right)... import xbmcplugin xbmcplugin.setPluginCategory(handle=int(sys.argv[1]), category="") xbmcplugin.addSortMethod(handle=int(sys.argv[1]), sortMethod=xbmcplugin.SORT_METHOD_NONE) xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True) if config.get_setting("forceview") == "true": # Confluence - Thumbnail import xbmc xbmc.executebuiltin("Container.SetViewMode(500)")
def getmainlist(): logger.info("channelselector.getmainlist") itemlist = [] # Obtiene el idioma, y el literal idioma = config.get_setting("languagefilter") logger.info("channelselector.getmainlist idioma=%s" % idioma) langlistv = [config.get_localized_string(30025),config.get_localized_string(30026),config.get_localized_string(30027),config.get_localized_string(30028),config.get_localized_string(30029)] try: idiomav = langlistv[int(idioma)] except: idiomav = langlistv[0] # Añade los canales que forman el menú principal itemlist.append( Item(title=config.get_localized_string(30118)+" ("+idiomav+")" , channel="channelselector" , action="channeltypes", thumbnail = urlparse.urljoin(get_thumbnail_path(),"channelselector.png") ) ) itemlist.append( Item(title=config.get_localized_string(30103) , channel="buscador" , action="mainlist" , thumbnail = urlparse.urljoin(get_thumbnail_path(),"buscador.png")) ) itemlist.append( Item(title=config.get_localized_string(30128) , channel="trailertools" , action="mainlist" , thumbnail = urlparse.urljoin(get_thumbnail_path(),"trailertools.png")) ) itemlist.append( Item(title=config.get_localized_string(30102) , channel="favoritos" , action="mainlist" , thumbnail = urlparse.urljoin(get_thumbnail_path(),"favoritos.png")) ) if config.get_platform() in ("wiimc","rss") :itemlist.append( Item(title="Wiideoteca (Beta)" , channel="wiideoteca" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(),"wiideoteca.png")) ) if config.get_platform()=="rss":itemlist.append( Item(title="pyLOAD (Beta)" , channel="pyload" , action="mainlist" , thumbnail = urlparse.urljoin(get_thumbnail_path(),"pyload.png")) ) itemlist.append( Item(title=config.get_localized_string(30101) , channel="descargas" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(),"descargas.png")) ) if "xbmceden" in config.get_platform(): itemlist.append( Item(title=config.get_localized_string(30100) , channel="configuracion" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(),"configuracion.png"), folder=False) ) else: itemlist.append( Item(title=config.get_localized_string(30100) , channel="configuracion" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(),"configuracion.png")) ) if config.get_setting("fileniumpremium")=="true": itemlist.append( Item(title="Torrents (Filenium)" , channel="descargasfilenium" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(),"torrents.png")) ) #if config.get_library_support(): if config.get_platform()!="rss": itemlist.append( Item(title=config.get_localized_string(30104) , channel="ayuda" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(),"ayuda.png")) ) return itemlist
def getchanneltypes(preferred_thumb=""): logger.info() # Lista de categorias channel_types = ["movie", "serie", "anime", "documentary", "vos", "torrent", "latino"] dict_types_lang = {'movie': config.get_localized_string(30122), 'serie': config.get_localized_string(30123), 'anime': config.get_localized_string(30124), 'documentary': config.get_localized_string(30125), 'vos': config.get_localized_string(30136), 'adult': config.get_localized_string(30126), 'latino': config.get_localized_string(30127)} if config.get_setting("adult_mode") != "0": channel_types.append("adult") channel_language = config.get_setting("channel_language") logger.info("channel_language="+channel_language) # Ahora construye el itemlist ordenadamente itemlist = list() title = config.get_localized_string(30121) itemlist.append(Item(title=title, channel="channelselector", action="filterchannels", category=title, channel_type="all", thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb), "thumb_canales_todos.png"), viewmode="thumbnails")) for channel_type in channel_types: logger.info("channel_type="+channel_type) title = dict_types_lang.get(channel_type, channel_type) itemlist.append(Item(title=title, channel="channelselector", action="filterchannels", category=title, channel_type=channel_type, viewmode="thumbnails", thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb), "thumb_canales_"+channel_type+".png"))) return itemlist
def login(): # Averigua el id de sesión data = scrapertools.cache_page("http://www.mocosoftx.com/foro/index.php") cur_session_id = scrapertools.get_match( data, 'form action="[^"]+" method="post" accept-charset="ISO-8859-1" onsubmit="hashLoginPassword\(this, \'([a-z0-9]+)\'', ) logger.info("cur_session_id=" + cur_session_id) # Calcula el hash del password LOGIN = config.get_setting("mocosoftxuser") PASSWORD = config.get_setting("mocosoftxpassword") logger.info("LOGIN="******"PASSWORD="******"hash_passwrd=" + hash_passwrd) # Hace el submit del login post = "user="******"&passwrd=&cookielength=-1&hash_passwrd=" + hash_passwrd logger.info("post=" + post) data = scrapertools.cache_page("http://mocosoftx.com/foro/login2/", post=post, headers=MAIN_HEADERS) return True
def get_data(payload): """ obtiene la información de la llamada JSON-RPC con la información pasada en payload @type payload: dict @param payload: data :return: """ logger.info("payload: %s" % payload) # Required header for XBMC JSON-RPC calls, otherwise you'll get a 415 HTTP response code - Unsupported media type headers = {'content-type': 'application/json'} if config.get_setting("library_mode", "biblioteca"): try: try: xbmc_port = int(config.get_setting("xbmc_puerto", "biblioteca")) except: xbmc_port = 0 xbmc_json_rpc_url = "http://" + config.get_setting("xbmc_host", "biblioteca") + ":" + str( xbmc_port) + "/jsonrpc" req = urllib2.Request(xbmc_json_rpc_url, data=jsontools.dump_json(payload), headers=headers) f = urllib2.urlopen(req) response = f.read() f.close() logger.info("get_data: response %s" % response) data = jsontools.load_json(response) except Exception, ex: template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) logger.info("get_data: error en xbmc_json_rpc_url: %s" % message) data = ["error"]
def menu(item): logger.info() # Opciones disponibles para el menu op = ["Descargar", "Eliminar de la lista", "Reiniciar descarga", "Descargar desde...", "Reproducir"] opciones = [] # Opciones para el menu if item.downloadStatus == 0: # Sin descargar opciones.append(op[0]) # Descargar opciones.append(op[3]) # Descargar desde... opciones.append(op[1]) # Eliminar de la lista if item.downloadStatus == 1: # descarga parcial opciones.append(op[0]) # Descargar opciones.append(op[2]) # Reiniciar descarga opciones.append(op[1]) # Eliminar de la lista if item.downloadStatus == 2: # descarga completada opciones.append(op[4]) # Reproducir opciones.append(op[1]) # Eliminar de la lista opciones.append(op[2]) # Reiniciar descarga if item.downloadStatus == 3: # descarga con error opciones.append(op[2]) # Reiniciar descarga opciones.append(op[1]) # Eliminar de la lista # Mostramos el dialogo seleccion = platformtools.dialog_select("Scegliere un'opzione", opciones) # -1 es cancelar if seleccion == -1: return logger.info("opcion=%s" % (opciones[seleccion])) # Opcion Eliminar if opciones[seleccion] == op[1]: filetools.remove(item.path) # Opcion inicaiar descarga if opciones[seleccion] == op[0]: start_download(item) # Opcion inicaiar descarga desde... if opciones[seleccion] == op[3]: start_download(item, ask=True) # Reiniciar descarga if opciones[seleccion] == op[2]: if filetools.isfile(os.path.join(config.get_setting("downloadpath"), item.downloadFilename)): filetools.remove(os.path.join(config.get_setting("downloadpath"), item.downloadFilename)) update_json(item.path, {"downloadStatus": STATUS_CODES.stoped, "downloadComplete": 0, "downloadProgress": 0}) # Reproducir if opciones[seleccion] == op[4]: item.url = filetools.join(DOWNLOAD_PATH, item.downloadFilename) return platformtools.play_video(item) platformtools.itemlist_refresh()
def login(item): if config.get_platform() in ("wiimc", "rss", "mediaserver"): login = config.get_setting("cinetubeuser") password = config.get_setting("cinetubepassword") if login<>"" and password<>"": url="http://www.cinetube.es/login.php" data = scrapertools.cache_page("http://www.cinetube.es/login.php",post="usuario=%s&clave=%s" % (login,password)) itemlist = [] itemlist.append( Item(channel=__channel__, title="Sesión iniciada", action="mainlist")) else: import xbmc keyboard = xbmc.Keyboard("","Login") keyboard.doModal() if (keyboard.isConfirmed()): login = keyboard.getText() keyboard = xbmc.Keyboard("","Password") keyboard.doModal() if (keyboard.isConfirmed()): password = keyboard.getText() nombre_fichero_config_canal = os.path.join( config.get_data_path() , __channel__+".xml" ) config_canal = open( nombre_fichero_config_canal , "w" ) config_canal.write("<settings>\n<session>true</session>\n<login>"+login+"</login>\n<password>"+password+"</password>\n</settings>") config_canal.close(); itemlist = [] itemlist.append( Item(channel=__channel__, title="Sesión iniciada", action="mainlist")) return itemlist
def MostrarMenuVideo(item,itemlist): opciones = [] Reproducible = False video_urls=0 seleccion = -1 for itemopcion in itemlist: opciones.append(itemopcion.title) if itemopcion.action=="play_video": Reproducible = True video_urls+=1 if len(opciones)>0: default_action = config.get_setting("default_action") if default_action=="0" or not Reproducible: #Preguntar seleccion = xbmcgui.Dialog().select(config.get_localized_string(30163), opciones) #"Elige una opción" elif default_action=="1": #Ver en Calidad Baja seleccion = 0 elif default_action=="2": #Ver en Calidad Alta seleccion = video_urls -1 elif default_action=="3": #Mandar a jDownloader if config.get_setting("jdownloader_enabled")=="true": seleccion = opciones.index(config.get_localized_string(30158)) #"Enviar a JDownloader" else: seleccion=0 return seleccion
def removefollow(tvs_id): user_id=config.get_setting("stormtvuser") user_pass=config.get_setting("stormtvpassword") #server= "https://"+__server__+"/stormtv/public/" #path=config.get_data_path()+"stormtv/temp/" urllib.urlretrieve (SERVER+"tvseries/removefollow/user/"+user_id+"/pass/"+user_pass+"/tvs/"+tvs_id, PATH+"temp.xml") print "[stormlib.py] Remove follow"
def get_temporadas(item): logger.info("streamondemand.channels.biblioteca get_temporadas") itemlist = [] dict_temp = {} raiz, carpetas_series, ficheros = filetools.walk(item.path).next() if config.get_setting("no_pile_on_seasons") == "Siempre": return get_episodios(item) for i in ficheros: if "tvshow" not in i: season = i.split('x')[0] dict_temp[season] = "Stagione " + str(season) if config.get_setting("no_pile_on_seasons") == "Solo se presente una stagione" and len(dict_temp) == 1: return get_episodios(item) else: # Creamos un item por cada temporada for season, title in dict_temp.items(): # fix para que se filtren bien los contenido, ya que sino se hereda el campo item.infoLabels['season'] = "" new_item = item.clone(action="get_episodios", title=title, contentTitle=title, contentSeason=season, contentEpisodeNumber="", filtrar_season=True, text_color="") itemlist.append(new_item) # logger.debug(new_item.tostring()) if len(itemlist) > 1: itemlist = sorted(itemlist, key=lambda it: int(it.contentSeason)) if config.get_setting("show_all_seasons") == "true": new_item = item.clone(action="get_episodios", title="*Tutte le stagioni", text_color="") itemlist.insert(0, new_item) return itemlist
def salvar_busquedas(params,url="",category=""): if url == "" and category == "": channel = params.channel url = params.url else: channel = params.get("channel") limite_busquedas = ( 10, 20, 30, 40, )[ int( config.get_setting( "limite_busquedas" ) ) ] matches = [] try: presets = config.get_setting("presets_buscados") if "|" in presets: presets = matches = presets.split("|") for count, preset in enumerate( presets ): if url in preset: del presets[ count ] break if len( presets ) >= limite_busquedas: presets = presets[ : limite_busquedas - 1 ] except: presets = "" presets2 = "" if len(matches)>0: for preset in presets: presets2 = presets2 + "|" + preset presets = url + presets2 elif presets != "": presets = url + "|" + presets else: presets = url config.set_setting("presets_buscados",presets)
def login(pagina): logger.info() try: user = config.get_setting("%suser" % pagina.split(".")[0], "copiapop") password = config.get_setting("%spassword" % pagina.split(".")[0], "copiapop") if pagina == "copiapop.com": if user == "" and password == "": return False, "Para ver los enlaces de copiapop es necesario registrarse en copiapop.com" elif user == "" or password == "": return False, "Copiapop: Usuario o contraseña en blanco. Revisa tus credenciales" else: if user == "" or password == "": return False, "DiskoKosmiko: Usuario o contraseña en blanco. Revisa tus credenciales" data = httptools.downloadpage("http://%s" % pagina).data if re.search(r'(?i)%s' % user, data): return True, "" token = scrapertools.find_single_match(data, 'name="__RequestVerificationToken".*?value="([^"]+)"') post = "__RequestVerificationToken=%s&UserName=%s&Password=%s" % (token, user, password) headers = {'X-Requested-With': 'XMLHttpRequest'} url_log = "http://%s/action/Account/Login" % pagina data = httptools.downloadpage(url_log, post, headers).data if "redirectUrl" in data: logger.info("Login correcto") return True, "" else: logger.info("Error en el login") return False, "Nombre de usuario no válido. Comprueba tus credenciales" except: import traceback logger.info(traceback.format_exc()) return False, "Error durante el login. Comprueba tus credenciales"
def login(): logger.info("channels.megahd login") # Averigua el id de sesión data = scrapertools.cache_page("http://megahd.me/login/", headers=MAIN_HEADERS) #<form action="http://megahd.me/login2/" name="frmLogin" id="frmLogin" method="post" accept-charset="UTF-8" onsubmit="hashLoginPassword(this, 'd3c3d7467c05a4058e9361996daeaed4');"> cur_session_id = scrapertools.get_match(data,'onsubmit\="hashLoginPassword\(this, \'([a-z0-9]+)\'') logger.info("channels.megahd cur_session_id="+cur_session_id) # Calcula el hash del password LOGIN = config.get_setting("megahduser") PASSWORD = config.get_setting("megahdpassword") logger.info("channels.megahd LOGIN="******"channels.megahd PASSWORD="******"channels.megahd hash_passwrd="+hash_passwrd) # Hace el submit del login post = "user="******"&passwrd=&cookieneverexp=on&hash_passwrd="+hash_passwrd logger.info("channels.megahd post="+post) data = scrapertools.cache_page("http://megahd.me/login2/" , post=post, headers=MAIN_HEADERS) return True
def send_to_jdownloader(item): #d = {"web": url}urllib.urlencode(d) from core import scrapertools if item.subtitle!="": data = scrapertools.cachePage(config.get_setting("jdownloader")+"/action/add/links/grabber0/start1/web="+item.url+ " " +item.thumbnail + " " + item.subtitle) else: data = scrapertools.cachePage(config.get_setting("jdownloader")+"/action/add/links/grabber0/start1/web="+item.url+ " " +item.thumbnail) return
def setwatched (tvs_id,chap_number): print"[stormlib.py] setwatched"+tvs_id+" "+chap_number user_id=config.get_setting("stormtvuser") user_pass=config.get_setting("stormtvpassword") #server= "https://"+__server__+"/stormtv/public/" #path=config.get_data_path()+"stormtv/temp/" print"[stormlib.py] setwatched "+SERVER+"chapters/add/tvs/"+tvs_id+"/user/"+user_id+"/pass/"+user_pass+"/chap/"+chap_number urllib.urlretrieve (SERVER+"chapters/add/tvs/"+tvs_id+"/user/"+user_id+"/pass/"+user_pass+"/chap/"+chap_number, PATH+"temp.xml")
# Canal para crunchyroll # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ # ------------------------------------------------------------ import re import urllib from core import config from core import httptools from core import jsontools as json from core import logger from core import scrapertools from core import tmdb from core.item import Item __perfil__ = config.get_setting('perfil', "crunchyroll") # Fijar perfil de color perfil = [ ['0xFFFFE6CC', '0xFFFFCE9C', '0xFF994D00', '0xFFFE2E2E', '0xFF088A08'], ['0xFFA5F6AF', '0xFF5FDA6D', '0xFF11811E', '0xFFFE2E2E', '0xFF088A08'], ['0xFF58D3F7', '0xFF2E9AFE', '0xFF2E64FE', '0xFFFE2E2E', '0xFF088A08'] ] if __perfil__ - 1 >= 0: color1, color2, color3, color4, color5 = perfil[__perfil__ - 1] else: color1 = color2 = color3 = color4 = color5 = "" host = "http://www.crunchyroll.com" proxy_u = "http://anonymouse.org/cgi-bin/anon-www.cgi/"
def run(): logger.info("pelisalacarta.platformcode.launcher run") # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") logger.info("pelisalacarta.platformcode.launcher "+item.tostring()) try: # If item has no action, stops here if item.action == "": logger.info("pelisalacarta.platformcode.launcher Item sin accion") return # Action for main menu in channelselector if item.action == "getmainlist": import channelselector itemlist = channelselector.getmainlist() # Check for updates only on first screen if config.get_setting("updatecheck2") == "true": logger.info("pelisalacarta.platformcode.launcher Check for plugin updates enabled") from core import updater try: version = updater.checkforupdates() if version: platformtools.dialog_ok("Versión "+version+" disponible", "Ya puedes descargar la nueva versión del plugin\n" "desde el listado principal") itemlist.insert(0, Item(title="Descargar version "+version, version=version, channel="updater", action="update", thumbnail=channelselector.get_thumbnail_path() + "Crystal_Clear_action_info.png")) except: platformtools.dialog_ok("No se puede conectar", "No ha sido posible comprobar", "si hay actualizaciones") logger.info("cpelisalacarta.platformcode.launcher Fallo al verificar la actualización") else: logger.info("pelisalacarta.platformcode.launcher Check for plugin updates disabled") platformtools.render_items(itemlist, item) # Action for updating plugin elif item.action == "update": from core import updater updater.update(item) if config.get_system_platform() != "xbox": import xbmc xbmc.executebuiltin("Container.Refresh") # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": # Parental control can_open_channel = False # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting("adult_pin") != "": tecleado = platformtools.dialog_input("", "PIN para canales de adultos", True) if tecleado is not None: if tecleado == config.get_setting("adult_pin"): can_open_channel = True # All the other cases can open the channel else: can_open_channel = True if not can_open_channel: return # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel+".py") logger.info("pelisalacarta.platformcode.launcher channel_file=%s" % channel_file) channel = None if item.channel in ["personal", "personal2", "personal3", "personal4", "personal5"]: import channels.personal as channel elif os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel]) except ImportError: exec "import channels."+item.channel+" as channel" logger.info("pelisalacarta.platformcode.launcher running channel "+channel.__name__+" "+channel.__file__) # Special play action if item.action == "play": logger.info("pelisalacarta.platformcode.launcher play") # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("pelisalacarta.platformcode.launcher executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0: item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok("plugin", "No hay nada para reproducir") # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("pelisalacarta.platformcode.launcher executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) # If not, uses the generic findvideos function else: logger.info("pelisalacarta.platformcode.launcher no channel 'findvideos' method, " "executing core method") from core import servertools itemlist = servertools.find_video_items(item) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": library.add_pelicula_to_library(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": library.add_serie_to_library(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from channels import descargas item.action = item.extra del item.extra descargas.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("pelisalacarta.platformcode.launcher search") last_search = "" last_search_active = config.get_setting("last_search", "buscador") if last_search_active: try: current_saved_searches_list = list(config.get_setting("saved_searches_list", "buscador")) last_search = current_saved_searches_list[0] except: pass tecleado = platformtools.dialog_input(last_search) if tecleado is not None: if last_search_active: from channels import buscador buscador.save_search(tecleado) tecleado = tecleado.replace(" ", "+") # TODO revisar 'personal.py' porque no tiene función search y daría problemas itemlist = channel.search(item, tecleado) else: itemlist = [] platformtools.render_items(itemlist, item) # For all other actions else: logger.info("pelisalacarta.platformcode.launcher executing channel '"+item.action+"' method") itemlist = getattr(channel, item.action)(item) platformtools.render_items(itemlist, item) except urllib2.URLError, e: import traceback logger.error("pelisalacarta.platformcode.launcher "+traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.info("pelisalacarta.platformcode.launcher Razon del error, codigo: "+str(e.reason[0])+", Razon: " + str(e.reason[1])) texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("plugin", texto) # Grab server response errors elif hasattr(e, 'code'): logger.info("pelisalacarta.platformcode.launcher codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok("plugin", config.get_localized_string(30051) % e.code)
import xbmc from core import config from core import logger from core import scrapertools from core.item import Item from servers import adfly from core import servertools __channel__ = "animeinstreaming" __category__ = "A" __type__ = "generic" __title__ = "AnimeInStreaming" __language__ = "IT" DEBUG = config.get_setting("debug") host = "http://animeinstreaming.net/" headers = [ ['User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:38.0) Gecko/20100101 Firefox/38.0'], ['Accept-Encoding', 'gzip, deflate'], ['Referer', host] ] def isGeneric(): return True # -----------------------------------------------------------------
from core import logger from core import scrapertools from core import servertools from core import tmdb from core.item import Item CHANNEL_HOST = "http://www.cinetux.net/" CHANNEL_DEFAULT_HEADERS = [ ["User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0"], ["Accept-Encoding", "gzip, deflate"], ["Referer", CHANNEL_HOST] ] # Configuracion del canal __modo_grafico__ = config.get_setting('modo_grafico', 'cinetux') __perfil__ = int(config.get_setting('perfil', 'cinetux')) # Fijar perfil de color perfil = [['0xFFFFE6CC', '0xFFFFCE9C', '0xFF994D00'], ['0xFFA5F6AF', '0xFF5FDA6D', '0xFF11811E'], ['0xFF58D3F7', '0xFF2E9AFE', '0xFF2E64FE']] color1, color2, color3 = perfil[__perfil__] DEBUG = config.get_setting("debug") fanart = "http://pelisalacarta.mimediacenter.info/fanart/cinetux.jpg" viewmode_options = {0: 'movie_with_plot', 1: 'movie', 2: 'list'} viewmode = viewmode_options[config.get_setting('viewmode', 'cinetux')] def mainlist(item):
def controller(plugin_name, port, host, path, headers): respuesta = "" respuesta += "version=7\n" respuesta += "logo=http://pelisalacarta.mimediacenter.info/icon.png\n" respuesta += "title=" + plugin_name + " " + VERSIONTAG + " (WiiMC)\n" respuesta += "\n" if path == "/wiimc/" or path == "/wiimc": import channelselector channelslist = channelselector.getmainlist() # Actualización automática de canales, actualiza la lista if config.get_setting("updatechannels") == "true": logger.info("Verificando actualización del channelselector") try: from core import updater actualizado = updater.updatechannel("channelselector") if actualizado: respuesta += "type=playlist\n" respuesta += "name=¡Lista de canales actualizada!\n" respuesta += "thumb=\n" respuesta += "URL=http://" + host + "/wiimc/\n" respuesta += "\n" except: import sys for line in sys.exc_info(): logger.error("%s" % line) for channel in channelslist: # Quita el canal de ayuda y el de configuración, no sirven en WiiMC if channel.channel != "configuracion" and channel.channel != "ayuda" and channel.channel != "trailertools": if channel.channel != "buscador": respuesta += "type=playlist\n" else: respuesta += "type=search\n" respuesta += "name=" + channel.title + "\n" respuesta += "thumb=http://" + plugin_name + ".mimediacenter.info/wiimc/" + channel.channel + ".png\n" respuesta += "URL=http://" + host + "/wiimc/" + base64.b64encode( channel.serialize()).replace("/", "%2F") + "/playlist.plx\n" respuesta += "\n" else: item = extract_item_from_url(path) if item.channel == "channelselector" and item.action == "channeltypes": import channelselector channelslist = channelselector.getchanneltypes() for channel in channelslist: if channel.category != "M" and channel.category != "G": respuesta += "type=playlist\n" respuesta += "name=" + channel.title + "\n" respuesta += "thumb=http://" + plugin_name + ".mimediacenter.info/wiimc/" + channel.channel + ".png\n" respuesta += "URL=http://" + host + "/wiimc/" + base64.b64encode( channel.serialize()).replace("/", "%2F") + "/playlist.plx\n" respuesta += "\n" elif item.channel == "channelselector" and item.action == "listchannels": import channelselector channelslist = channelselector.filterchannels(item.category) for channel in channelslist: if channel.type == "generic" or channel.type == "wiimc": channel.action = "mainlist" respuesta += "type=playlist\n" respuesta += "name=" + channel.title + "\n" respuesta += "thumb=http://" + plugin_name + ".mimediacenter.info/wiimc/" + channel.channel + ".png\n" respuesta += "URL=http://" + host + "/wiimc/" + base64.b64encode( channel.serialize()).replace("/", "%2F") + "/playlist.plx\n" respuesta += "\n" else: itemlist, channel = getitems(item, path) # Las listas vacías son problemáticas, añade un elemento dummy if len(itemlist) == 0: itemlist.append(Item(title="(No hay elementos)")) for item in itemlist: if item.action == "search" or item.action == "login" or item.action == "password": if item.server == "": item.server = "none" if item.url == "": item.url = "none" url = "http://%s/%s/playlist.plx" % ( host + "/wiimc", base64.b64encode( item.serialize()).replace("/", "%2F")) respuesta += "type=search\n" respuesta += "name=%s\n" % item.title if item.thumbnail != "": respuesta += "thumb=%s\n" % item.thumbnail respuesta += "URL=%s\n" % url respuesta += "\n" if item.action == "search": logger.info(" Buscador " + url) else: logger.info(" Login " + url) elif item.folder or item.action == "play" or item.action == "downloadall": if item.server == "": item.server = "none" if item.url == "": item.url = "none" if item.title == "": item.title = "Ver el video-" url = "http://%s/%s/playlist.plx" % ( host + "/wiimc", base64.b64encode( item.serialize()).replace("/", "%2F")) respuesta += "type=playlist\n" respuesta += "name=%s\n" % item.title if item.thumbnail != "": respuesta += "thumb=%s\n" % item.thumbnail respuesta += "URL=%s\n" % url respuesta += "\n" logger.info(" Nivel intermedio " + url) else: respuesta += "type=video\n" respuesta += "name=%s\n" % item.title respuesta += "URL=%s\n" % item.url respuesta += "\n" logger.info(" Video " + item.url) return respuesta
# pelisalacarta - XBMC Plugin # Canal para Descargasmix # Por SeiTaN, robalo y Cmos # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import re import urllib from core import config from core import logger from core import scrapertools from core import servertools from core.item import Item __modo_grafico__ = config.get_setting("modo_grafico", "descargasmix") __perfil__ = int(config.get_setting("perfil", "descargasmix")) # Fijar perfil de color perfil = [['0xFFFFE6CC', '0xFFFFCE9C', '0xFF994D00'], ['0xFFA5F6AF', '0xFF5FDA6D', '0xFF11811E'], ['0xFF58D3F7', '0xFF2E9AFE', '0xFF2E64FE']] color1, color2, color3 = perfil[__perfil__] DEBUG = config.get_setting("debug") DEFAULT_HEADERS = [["User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0"]] def mainlist(item): logger.info("pelisalacarta.channels.descargasmix mainlist") itemlist = []
def episodios(item): logger.info("pelisalacarta.channels.seriesdanko episodios") if config.get_platform()=="xbmc" or config.get_platform()=="xbmcdharma": import xbmc if config.get_setting("forceview")=="true": xbmc.executebuiltin("Container.SetViewMode(53)") #53=icons #xbmc.executebuiltin("Container.Content(Movies)") item.url = item.url.replace("../","") ## Corrige los enlaces que vienen de search if "|" in item.url: url = item.url.split("|")[0] sw = True else: url = item.url sw = False # Descarga la página if item.extra: contenidos = item.extra #print contenidos else: data = scrapertools.downloadpageWithoutCookies(url) # Extrae las entradas if sw: try: datadict = eval( "(" + data + ")" ) data = urllib.unquote_plus(datadict["entry"]["content"]["$t"].replace("\\u00","%")) matches=[] matches.append(data) except: matches = [] else: patronvideos = "entry-content(.*?)<div class='blog-pager' id='blog-pager'>" matches = re.compile(patronvideos,re.DOTALL).findall(data) if len(matches)>0: contenidos = matches[0].replace('"',"'").replace("\n","") else: contenidos = item.url if sw: url = item.url.split("|")[1] if not url.startswith("http://"): url = urlparse.urljoin("http://seriesdanko.com",url) # Descarga la página data = scrapertools.downloadpageGzip(url) patronvideos = "entry-content(.*?)<div class='post-footer'>" matches = re.compile(patronvideos,re.DOTALL).findall(data) if len(matches)>0: contenidos = matches[0] patronvideos = "<a href='([^']+)'>([^<]+)</a> <img(.+?)/>" matches = re.compile(patronvideos,re.DOTALL).findall(contenidos.replace('"',"'")) #print contenidos try: plot = re.compile(r'(Informac.*?/>)</div>').findall(contenidos)[0] if len(plot)==0: plot = re.compile(r"(Informac.*?both;'>)</div>").findall(contenidos)[0] plot = re.sub('<[^>]+>'," ",plot) except: plot = "" itemlist = [] for match in matches: scrapedtitle = match[1].replace("\n","").replace("\r","") logger.info("scrapedtitle="+scrapedtitle) ## Eliminado para la opción "Añadir esta serie a la biblioteca de XBMC" (15-12-2014) #scrapedtitle = scrapertools.remove_show_from_title(scrapedtitle,item.show) episode_code = scrapertools.find_single_match(scrapedtitle,"(\d+X\d+)") logger.info("episode_code="+episode_code) if episode_code!="": season_number = scrapertools.find_single_match(scrapedtitle,"(\d+)X\d+") logger.info("season_number="+season_number) episode_number = scrapertools.find_single_match(scrapedtitle,"\d+X(\d+)") logger.info("episode_number="+episode_number) new_episode_code = season_number+"x"+episode_number logger.info("new_episode_code="+new_episode_code) scrapedtitle = scrapedtitle.replace(episode_code,new_episode_code) logger.info("scrapedtitle="+scrapedtitle) #[1x01 - Capitulo 01] #patron = "(\d+x\d+) - Capitulo \d+" #matches = re.compile(patron,re.DOTALL).findall(scrapedtitle) #print matches #if len(matches)>0 and len(matches[0])>0: # scrapedtitle = matches[0] if "es.png" in match[2]: subtitle = " (Español)" elif "la.png" in match[2]: subtitle = " (Latino)" elif "vo.png" in match[2]: subtitle = " (VO)" elif "vos.png" in match[2]: subtitle = " (VOS)" elif "ca.png" in match[2]: subtitle = " (Catalan)" elif "ga.jpg" in match[2]: subtitle = " (Gallego)" elif "eu.jpg" in match[2]: subtitle = " (Euskera)" elif "ba.png" in match[2]: subtitle = " (Bable)" else: subtitle = "" scrapedplot = plot scrapedurl = urlparse.urljoin(item.url,match[0]).replace("\n","").replace("\r","") if not item.thumbnail: try: scrapedthumbnail = re.compile(r"src=([^']+)'").findall(contenidos)[0] except: scrapedthumbnail = "" else: scrapedthumbnail = item.thumbnail scrapedthumbnail = scrapedthumbnail.replace("\n","").replace("\r","") if item.fulltitle == '': item.fulltitle = scrapedtitle + subtitle if (DEBUG): logger.info("title=["+scrapedtitle+"], url=["+scrapedurl+"], thumbnail=["+scrapedthumbnail+"]") ## Añadido show para la opción "Añadir esta serie a la biblioteca de XBMC" (15-12-2014) # Añade al listado de XBMC itemlist.append( Item(channel=__channel__, action="findvideos", title=scrapedtitle+subtitle , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , fulltitle = item.fulltitle, context="4", show=item.show, folder=True) ) if (config.get_platform().startswith("xbmc") or config.get_platform().startswith("boxee")) and len(itemlist)>0: itemlist.append( Item(channel=item.channel, title="Añadir esta serie a la biblioteca de XBMC", url=item.url, action="add_serie_to_library", extra="episodios###", show=item.show)) itemlist.append( Item(channel=item.channel, title="Descargar todos los episodios de la serie", url=item.url, action="download_all_episodes", extra="episodios###", show=item.show)) #xbmc.executebuiltin("Container.Content(Movies)") if len(itemlist)==0: listvideos = servertools.findvideos(contenidos) for title,url,server in listvideos: if server == "youtube": scrapedthumbnail = "http://i.ytimg.com/vi/" + url + "/0.jpg" else: scrapedthumbnail = item.thumbnail scrapedtitle = title scrapedplot = "" scrapedurl = url if (DEBUG): logger.info("title=["+scrapedtitle+"], url=["+scrapedurl+"], thumbnail=["+scrapedthumbnail+"]") # Añade al listado de XBMC itemlist.append( Item(channel=__channel__, action="play", server=server, title=item.title +" "+ scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot, fulltitle = scrapedtitle , folder=False) ) return itemlist
def findvideos(item): logger.info("[newpct1.py] findvideos") itemlist = [] ## Cualquiera de las tres opciones son válidas #item.url = item.url.replace("1.com/","1.com/ver-online/") #item.url = item.url.replace("1.com/","1.com/descarga-directa/") item.url = item.url.replace("1.com/", "1.com/descarga-torrent/") # Descarga la página data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", scrapertools.cache_page(item.url)) data = unicode(data, "iso-8859-1", errors="replace").encode("utf-8") title = scrapertools.find_single_match( data, "<h1><strong>([^<]+)</strong>[^<]+</h1>") title += scrapertools.find_single_match( data, "<h1><strong>[^<]+</strong>([^<]+)</h1>") caratula = scrapertools.find_single_match( data, '<div class="entry-left">.*?src="([^"]+)"') #<a href="http://tumejorjuego.com/download/index.php?link=descargar-torrent/058310_yo-frankenstein-blurayrip-ac3-51.html" title="Descargar torrent de Yo Frankenstein " class="btn-torrent" target="_blank">Descarga tu Archivo torrent!</a> patron = '<a href="([^"]+)" title="[^"]+" class="btn-torrent" target="_blank">' # escraped torrent url = scrapertools.find_single_match(data, patron) if url != "": itemlist.append( Item(channel=__channel__, action="play", server="torrent", title=title + " [torrent]", fulltitle=title, url=url, thumbnail=caratula, plot=item.plot, folder=False)) # escraped ver vídeos, descargar vídeos un link, múltiples liks data = data.replace("'", '"') data = data.replace( 'javascript:;" onClick="popup("http://www.newpct1.com/pct1/library/include/ajax/get_modallinks.php?links=', "") data = data.replace( "http://tumejorserie.com/descargar/url_encript.php?link=", "") data = data.replace("$!", "#!") patron_descargar = '<div id="tab2"[^>]+>.*?</ul>' patron_ver = '<div id="tab3"[^>]+>.*?</ul>' match_ver = scrapertools.find_single_match(data, patron_ver) match_descargar = scrapertools.find_single_match(data, patron_descargar) patron = '<div class="box1"><img src="([^"]+)".*?' # logo patron += '<div class="box2">([^<]+)</div>' # servidor patron += '<div class="box3">([^<]+)</div>' # idioma patron += '<div class="box4">([^<]+)</div>' # calidad patron += '<div class="box5"><a href="([^"]+)".*?' # enlace patron += '<div class="box6">([^<]+)</div>' # titulo enlaces_ver = re.compile(patron, re.DOTALL).findall(match_ver) enlaces_descargar = re.compile(patron, re.DOTALL).findall(match_descargar) for logo, servidor, idioma, calidad, enlace, titulo in enlaces_ver: servidor = servidor.replace("played", "playedto") titulo = titulo + " [" + servidor + "]" mostrar_server = True if config.get_setting("hidepremium") == "true": mostrar_server = servertools.is_server_enabled(servidor) if mostrar_server: itemlist.append( Item(channel=__channel__, action="play", server=servidor, title=titulo, fulltitle=item.title, url=enlace, thumbnail=logo, plot=item.plot, folder=False)) for logo, servidor, idioma, calidad, enlace, titulo in enlaces_descargar: servidor = servidor.replace("uploaded", "uploadedto") partes = enlace.split(" ") p = 1 for enlace in partes: parte_titulo = titulo + " (%s/%s)" % ( p, len(partes)) + " [" + servidor + "]" p += 1 mostrar_server = True if config.get_setting("hidepremium") == "true": mostrar_server = servertools.is_server_enabled(servidor) if mostrar_server: itemlist.append( Item(channel=__channel__, action="play", server=servidor, title=parte_titulo, fulltitle=item.title, url=enlace, thumbnail=logo, plot=item.plot, folder=False)) return itemlist
def findvideos(item): logger.info("pelisalacarta.channels.descargasmix findvideos") if item.extra and item.extra != "findvideos": return epienlaces(item) itemlist = [] item.text_color = color3 data = scrapertools.downloadpage(item.url) item.plot = scrapertools.find_single_match(data, 'SINOPSIS(?:</span>|</strong>):(.*?)</p>') year = scrapertools.find_single_match(data, '(?:<span class="bold">|<strong>)AÑO(?:</span>|</strong>):\s*(\d+)') if year != "": try: from core import tmdb item.infoLabels['year'] = year tmdb.set_infoLabels_item(item, __modo_grafico__) except: pass old_format = False #Patron torrent antiguo formato if "Enlaces de descarga</div>" in data: old_format = True matches = scrapertools.find_multiple_matches(data, 'class="separate3 magnet".*?href="([^"]+)"') for scrapedurl in matches: title = "[Torrent] " title += urllib.unquote(scrapertools.find_single_match(scrapedurl, 'dn=(.*?)(?i)WWW.DescargasMix')) itemlist.append(item.clone(action="play", server="torrent", title=title, url=scrapedurl, text_color="green")) #Patron online data_online = scrapertools.find_single_match(data, 'Ver online</div>(.*?)<div class="section-box related-' 'posts">') if len(data_online) > 0: itemlist.append(item.clone(title="Enlaces Online", action="", text_color=color1)) patron = 'dm\(c.a\(\'([^\']+)\'' matches = scrapertools.find_multiple_matches(data_online, patron) for code in matches: enlace = dm(code) enlaces = servertools.findvideos(data=enlace) if len(enlaces) > 0: title = " Ver vídeo en " + enlaces[0][2] itemlist.append(item.clone(action="play", server=enlaces[0][2], title=title, url=enlaces[0][1])) #Patron descarga bloques_descarga = scrapertools.find_multiple_matches(data, '<div class="floatLeft double(?:nuevo|)">(.*?)</div>(.*?)(?:<div id="mirrors"|<script>)') for title_bloque, bloque in bloques_descarga: if title_bloque == "Ver online": continue itemlist.append(item.clone(title=title_bloque, action="", text_color=color1)) patron = '<div class="fondoenlaces".*?id=".*?_([^"]+)".*?textContent=nice=dm\(c.a\(\'([^\']+)\'' matches = scrapertools.find_multiple_matches(bloque, patron) for scrapedserver, scrapedurl in matches: if (scrapedserver == "ul") | (scrapedserver == "uploaded"): scrapedserver = "uploadedto" titulo = scrapedserver.capitalize() if titulo == "Magnet" and old_format: continue elif titulo == "Magnet" and not old_format: title = " Enlace Torrent" itemlist.append(item.clone(action="play", server="torrent", title=title, url=scrapedurl, text_color="green")) continue mostrar_server = True if config.get_setting("hidepremium") == "true": mostrar_server = servertools.is_server_enabled(scrapedserver) if mostrar_server: try: servers_module = __import__("servers."+scrapedserver) #Saca numero de enlaces patron = "(dm\(c.a\('"+scrapedurl.replace("+", "\+")+"'.*?)</div>" data_enlaces = scrapertools.find_single_match(bloque, patron) patron = 'dm\(c.a\(\'([^\']+)\'' matches_enlaces = scrapertools.find_multiple_matches(data_enlaces, patron) numero = str(len(matches_enlaces)) titulo = " "+titulo+" - Nº enlaces:"+numero itemlist.append(item.clone(action="enlaces", title=titulo, extra=scrapedurl)) except: pass itemlist.append(item.clone(channel="trailertools", title="Buscar Tráiler", action="buscartrailer", context="", text_color="magenta")) if item.extra != "findvideos" and config.get_library_support(): itemlist.append(Item(channel=item.channel, title="Añadir a la biblioteca", action="add_pelicula_to_library", extra="findvideos", url=item.url, infoLabels={'title': item.fulltitle}, fulltitle=item.fulltitle, text_color="green")) return itemlist
def getmainlist(preferred_thumb=""): logger.info("channelselector.getmainlist") itemlist = [] if config.get_setting("programs_enable_section") == "true": if config.get_setting("programs_enable_subsections") != "true": itemlist.append( Item(title="Programas", channel="api_programas", action="mainlist", thumbnail=urlparse.urljoin( get_thumbnail_path(preferred_thumb), "menu/updated.png"))) else: itemlist.append( Item(title="Programas", channel="api_programas", action="programas", thumbnail=api.get_section_thumbnail("programas"))) itemlist.append( Item(title="Informativos", channel="api_programas", action="informativos", thumbnail=api.get_section_thumbnail("informativos"))) itemlist.append( Item(title="Deportes", channel="api_programas", action="deportes", thumbnail=api.get_section_thumbnail("deportes"))) itemlist.append( Item(title="Series", channel="api_programas", action="series", thumbnail=api.get_section_thumbnail("series"))) itemlist.append( Item(title="Infantil", channel="api_programas", action="infantil", thumbnail=api.get_section_thumbnail("infantil"))) itemlist.append( Item(title="Cine", channel="api_programas", action="cine", thumbnail=api.get_section_thumbnail("cine"))) itemlist.append( Item(title="Canales", channel="channelselector", action="channeltypes", thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb), "menu/channels.png"))) #itemlist.append( Item(title="Buscador" , channel="buscador" , action="mainlist" , thumbnail = urlparse.urljoin(get_thumbnail_path(preferred_thumb),"menu/search.png")) ) itemlist.append( Item(title="Descargas", channel="descargas", action="mainlist", thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb), "menu/downloads.png"))) itemlist.append( Item(title="Favoritos", channel="favoritos", action="mainlist", thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb), "menu/favorites.png"))) itemlist.append( Item(title="Configuración", channel="configuracion", action="mainlist", thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb), "menu/settings.png"))) itemlist.append( Item(title="Ayuda", channel="ayuda", action="mainlist", thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb), "menu/help.png"))) return itemlist
def addfolder(nombre, channelname, accion, category="", thumbnailname="", folder=True): #print "addfolder" if category == "": try: category = unicode(nombre, "utf-8").encode("iso-8859-1") except: pass import xbmc if config.get_setting("thumbnail_type") == "0": IMAGES_PATH = xbmc.translatePath( os.path.join(config.get_runtime_path(), 'resources', 'images', 'posters')) elif config.get_setting("thumbnail_type") == "1": IMAGES_PATH = xbmc.translatePath( os.path.join(config.get_runtime_path(), 'resources', 'images', 'banners')) elif config.get_setting("thumbnail_type") == "2": IMAGES_PATH = xbmc.translatePath( os.path.join(config.get_runtime_path(), 'resources', 'images', 'squares')) if config.get_setting("thumbnail_type") == "0": WEB_PATH = "http://media.tvalacarta.info/tvalacarta/posters/" elif config.get_setting("thumbnail_type") == "1": WEB_PATH = "http://media.tvalacarta.info/tvalacarta/banners/" elif config.get_setting("thumbnail_type") == "2": WEB_PATH = "http://media.tvalacarta.info/tvalacarta/squares/" if config.get_platform() == "boxee": IMAGES_PATH = "http://media.tvalacarta.info/tvalacarta/posters/" if thumbnailname == "": thumbnailname = channelname ''' thumbnail = os.path.join(IMAGES_PATH, "menu", thumbnailname) #logger.info("thumbnail="+thumbnail) if not os.path.exists(thumbnail): # Preferencia: primero JPG thumbnail = os.path.join(IMAGES_PATH, thumbnailname+".jpg") # Preferencia: segundo PNG if not os.path.exists(thumbnail): thumbnail = os.path.join(IMAGES_PATH, thumbnailname+".png") # Preferencia: tercero WEB if not os.path.exists(thumbnail): ''' if thumbnailname.startswith("http://") or thumbnailname.startswith( "https://"): thumbnail = thumbnailname else: thumbnail = WEB_PATH + thumbnailname + ".png" import xbmcgui import xbmcplugin #logger.info("thumbnail="+thumbnail) listitem = xbmcgui.ListItem(nombre, iconImage="DefaultFolder.png", thumbnailImage=thumbnail) itemurl = '%s?channel=%s&action=%s&category=%s' % ( sys.argv[0], channelname, accion, category) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=itemurl, listitem=listitem, isFolder=folder)
def porGenero(item): logger.info("[pelisadicto.py] porGenero") itemlist = [] itemlist.append( Item(channel=item.channel, action="agregadas", title="Acción", url="http://pelisadicto.com/genero/Acción/1", viewmode="movie_with_plot")) if config.get_setting("adult_mode") == "true": itemlist.append( Item(channel=item.channel, action="agregadas", title="Adulto", url="http://pelisadicto.com/genero/Adulto/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Animación", url="http://pelisadicto.com/genero/Animación/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Aventura", url="http://pelisadicto.com/genero/Aventura/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Biográfico", url="http://pelisadicto.com/genero/Biográfico/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Ciencia Ficción", url="http://pelisadicto.com/genero/Ciencia Ficción/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Cine Negro", url="http://pelisadicto.com/genero/Cine Negro/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Comedia", url="http://pelisadicto.com/genero/Comedia/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Corto", url="http://pelisadicto.com/genero/Corto/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Crimen", url="http://pelisadicto.com/genero/Crimen/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Deporte", url="http://pelisadicto.com/genero/Deporte/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Documental", url="http://pelisadicto.com/genero/Documental/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Drama", url="http://pelisadicto.com/genero/Drama/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Familiar", url="http://pelisadicto.com/genero/Familiar/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Fantasía", url="http://pelisadicto.com/genero/Fantasía/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Guerra", url="http://pelisadicto.com/genero/Guerra/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Historia", url="http://pelisadicto.com/genero/Historia/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Misterio", url="http://pelisadicto.com/genero/Misterio/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Música", url="http://pelisadicto.com/genero/Música/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Musical", url="http://pelisadicto.com/genero/Musical/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Romance", url="http://pelisadicto.com/genero/Romance/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Terror", url="http://pelisadicto.com/genero/Terror/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Thriller", url="http://pelisadicto.com/genero/Thriller/1", viewmode="movie_with_plot")) itemlist.append( Item(channel=item.channel, action="agregadas", title="Western", url="http://pelisadicto.com/genero/Western/1", viewmode="movie_with_plot")) return itemlist
def find_and_set_infoLabels(item): """ función que se llama para buscar y setear los infolabels :param item: :return: boleano que indica si se ha podido encontrar el 'code' """ global scraper scraper = None # logger.debug("item:\n" + item.tostring('\n')) list_opciones_cuadro = ["Immettere un altro nome", "Informazioni complete"] # Si se añaden más scrapers hay q declararlos aqui-> "modulo_scraper": "Texto_en_cuadro" scrapers_disponibles = { 'tmdb': "Cerca su TheMovieDB.org", 'tvdb': "Cerca su TheTvDB.com" } # Obtener el Scraper por defecto de la configuracion segun el tipo de contenido if item.contentType == "movie": scraper_actual = ['tmdb'][config.get_setting("scraper_movies", "biblioteca")] tipo_contenido = "película" title = item.contentTitle # Completar lista de opciones para este tipo de contenido list_opciones_cuadro.append(scrapers_disponibles['tmdb']) else: scraper_actual = ['tmdb', 'tvdb'][config.get_setting("scraper_tvshows", "biblioteca")] tipo_contenido = "serie" title = item.contentSerieName # Completar lista de opciones para este tipo de contenido list_opciones_cuadro.append(scrapers_disponibles['tmdb']) list_opciones_cuadro.append(scrapers_disponibles['tvdb']) # Importamos el scraper try: scraper = __import__('core.%s' % scraper_actual, fromlist=["core.%s" % scraper_actual]) except ImportError: exec "import core." + scraper_actual + " as scraper" except: import traceback logger.error(traceback.format_exc()) while scraper: # Llamamos a la funcion find_and_set_infoLabels del scraper seleccionado scraper_result = scraper.find_and_set_infoLabels(item) # Verificar si existe 'code' if scraper_result and item.infoLabels['code']: # code correcto logger.info("Identificador encontrado: %s" % item.infoLabels['code']) scraper.completar_codigos(item) return True elif scraper_result: # Contenido encontrado pero no hay 'code' msg = "ID Non trovato per: %s" % title else: # Contenido no encontrado msg = "Nessuna informazione trovata per: %s" % title logger.info(msg) # Mostrar cuadro con otras opciones: if scrapers_disponibles[scraper_actual] in list_opciones_cuadro: list_opciones_cuadro.remove(scrapers_disponibles[scraper_actual]) index = platformtools.dialog_select(msg, list_opciones_cuadro) if index < 0: logger.debug("Se ha pulsado 'cancelar' en la ventana '%s'" % msg) return False elif index == 0: # Pregunta el titulo title = platformtools.dialog_input( title, "Inserire il nome %s per ricerca" % tipo_contenido) if title: if item.contentType == "movie": item.contentTitle = title else: item.contentSerieName = title else: logger.debug( "he pulsado 'cancelar' en la ventana 'Introduzca el nombre correcto'" ) return False elif index == 1: # Hay q crear un cuadro de dialogo para introducir los datos logger.info("Completar información") if cuadro_completar(item): # code correcto logger.info("Identificador encontrado: %s" % str(item.infoLabels['code'])) return True # raise elif list_opciones_cuadro[index] in scrapers_disponibles.values(): # Obtener el nombre del modulo del scraper for k, v in scrapers_disponibles.items(): if list_opciones_cuadro[index] == v: if scrapers_disponibles[ scraper_actual] not in list_opciones_cuadro: list_opciones_cuadro.append( scrapers_disponibles[scraper_actual]) # Importamos el scraper k scraper_actual = k try: scraper = None scraper = __import__( 'core.%s' % scraper_actual, fromlist=["core.%s" % scraper_actual]) except ImportError: exec "import core." + scraper_actual + " as scraper_module" break logger.error("Error al importar el modulo scraper %s" % scraper_actual)
def do_search(item): logger.info("streamondemand.channels.buscador do_search") if '{}' in item.extra: tecleado, category = item.extra.split('{}') else: tecleado = item.extra category = "" itemlist = [] channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml') logger.info("streamondemand.channels.buscador channels_path=" + channels_path) channel_language = config.get_setting("channel_language") logger.info("streamondemand.channels.buscador channel_language=" + channel_language) if channel_language == "": channel_language = "all" logger.info("streamondemand.channels.buscador channel_language=" + channel_language) progreso = platformtools.dialog_progress_bg("Cercando " + urllib.unquote_plus(tecleado), "") channel_files = sorted(glob.glob(channels_path)) number_of_channels = 0 completed_channels = 0 search_results = Queue.Queue() start_time = int(time.time()) for infile in channel_files: basename_without_extension = os.path.basename(infile)[:-4] channel_parameters = channeltools.get_channel_parameters(basename_without_extension) # No busca si es un canal inactivo if channel_parameters["active"] != True: continue # En caso de busqueda por categorias if category and category not in channel_parameters["categories"]: continue # No busca si es un canal para adultos, y el modo adulto está desactivado if channel_parameters["adult"] == True and config.get_setting("adult_mode") == False: continue # No busca si el canal es en un idioma filtrado if channel_language != "all" and channel_parameters["language"] != channel_language: continue # No busca si es un canal excluido de la busqueda global include_in_global_search = channel_parameters["include_in_global_search"] if include_in_global_search == True: # Buscar en la configuracion del canal include_in_global_search = config.get_setting("include_in_global_search", basename_without_extension) if include_in_global_search == False: continue t = Thread(target=channel_search, args=[search_results, channel_parameters, category, tecleado]) t.setDaemon(True) t.start() number_of_channels += 1 while threading.active_count() >= MAX_THREADS: delta_time = int(time.time()) - start_time if len(itemlist) <= 0: timeout = None # No result so far,lets the thread to continue working until a result is returned elif delta_time >= TIMEOUT_TOTAL: progreso.close() itemlist = sorted(itemlist, key=lambda item: item.fulltitle) return itemlist else: timeout = TIMEOUT_TOTAL - delta_time # Still time to gather other results progreso.update(completed_channels * 100 / number_of_channels) try: itemlist.extend(search_results.get(timeout=timeout)) completed_channels += 1 except: progreso.close() itemlist = sorted(itemlist, key=lambda item: item.fulltitle) return itemlist while completed_channels < number_of_channels: delta_time = int(time.time()) - start_time if len(itemlist) <= 0: timeout = None # No result so far,lets the thread to continue working until a result is returned elif delta_time >= TIMEOUT_TOTAL: break # At least a result matching the searched title has been found, lets stop the search else: timeout = TIMEOUT_TOTAL - delta_time # Still time to gather other results progreso.update(completed_channels * 100 / number_of_channels) try: itemlist.extend(search_results.get(timeout=timeout)) completed_channels += 1 except: # Expired timeout raise an exception break progreso.close() itemlist = sorted(itemlist, key=lambda item: item.fulltitle) return itemlist
# -*- coding: utf-8 -*- import re import threading from core import config from core import filetools from core import httptools from core import logger from core import scrapertools from core.item import Item __perfil__ = config.get_setting('perfil', "copiapop") # Fijar perfil de color perfil = [['0xFFFFE6CC', '0xFFFFCE9C', '0xFF994D00', '0xFFFE2E2E', '0xFF088A08'], ['0xFFA5F6AF', '0xFF5FDA6D', '0xFF11811E', '0xFFFE2E2E', '0xFF088A08'], ['0xFF58D3F7', '0xFF2E9AFE', '0xFF2E64FE', '0xFFFE2E2E', '0xFF088A08']] if __perfil__ - 1 >= 0: color1, color2, color3, color4, color5 = perfil[__perfil__ - 1] else: color1 = color2 = color3 = color4 = color5 = "" adult_content = config.get_setting("adult_content", "copiapop") def login(pagina): logger.info() try:
def searchSubtitle(item): if config.get_setting("subtitle_type") == "0": subtitlepath = config.get_setting("subtitlepath_folder") if subtitlepath == "": subtitlepath = os.path.join(config.get_data_path(), "subtitles") config.set_setting("subtitlepath_folder", subtitlepath) elif config.get_setting("subtitle_type") == "1": subtitlepath = config.get_setting("subtitlepath_keyboard") if subtitlepath == "": subtitlepath = os.path.join(config.get_data_path(), "subtitles") config.set_setting("subtitlepathkeyboard", subtitlepath) elif subtitlepath.startswith("http"): subtitlepath = config.get_setting("subtitlepath_folder") else: subtitlepath = config.get_setting("subtitlepath_folder") if subtitlepath == "": subtitlepath = os.path.join(config.get_data_path(), "subtitles") config.set_setting("subtitlepath_folder", subtitlepath) if not os.path.exists(subtitlepath): try: os.mkdir(subtitlepath) except: logger.info("error no se pudo crear path subtitulos") return path_movie_subt = xbmc.translatePath(os.path.join(subtitlepath, "Movies")) if not os.path.exists(path_movie_subt): try: os.mkdir(path_movie_subt) except: logger.info("error no se pudo crear el path Movies") return full_path_tvshow = "" path_tvshow_subt = xbmc.translatePath(os.path.join(subtitlepath, "Tvshows")) if not os.path.exists(path_tvshow_subt): try: os.mkdir(path_tvshow_subt) except: logger.info("error no pudo crear el path Tvshows") return if item.show in item.title: title_new = title = urllib.unquote_plus(item.title) else: title_new = title = urllib.unquote_plus(item.show + " - " + item.title) path_video_temp = xbmc.translatePath( os.path.join(config.get_runtime_path(), "resources", "subtitle.mp4")) if not os.path.exists(path_video_temp): logger.info("error : no existe el video temporal de subtitulos") return #path_video_temp = xbmc.translatePath(os.path.join( ,video_temp + ".mp4" )) title_new = _normalize(title_new) tvshow_title, season, episode = regex_tvshow(False, title_new) if episode != "": full_path_tvshow = xbmc.translatePath( os.path.join(path_tvshow_subt, tvshow_title)) if not os.path.exists(full_path_tvshow): os.mkdir(full_path_tvshow) #title_new + ".mp4" full_path_video_new = xbmc.translatePath( os.path.join(full_path_tvshow, "%s %sx%s.mp4" % (tvshow_title, season, episode))) logger.info(full_path_video_new) listitem = xbmcgui.ListItem(title_new, iconImage="DefaultVideo.png", thumbnailImage="") listitem.setInfo( "video", { "Title": title_new, "Genre": "Tv shows", "episode": int(episode), "season": int(season), "tvshowtitle": tvshow_title }) else: full_path_video_new = xbmc.translatePath( os.path.join(path_movie_subt, title_new + ".mp4")) listitem = xbmcgui.ListItem(title, iconImage="DefaultVideo.png", thumbnailImage="") listitem.setInfo("video", {"Title": title_new, "Genre": "Movies"}) import shutil, time try: shutil.copy(path_video_temp, full_path_video_new) copy = True logger.info("nuevo path =" + full_path_video_new) time.sleep(2) playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() playlist.add(full_path_video_new, listitem) #xbmcPlayer = xbmc.Player( xbmc.PLAYER_CORE_AUTO ) xbmcPlayer = xbmc.Player() xbmcPlayer.play(playlist) #xbmctools.launchplayer(full_path_video_new,listitem) except: copy = False logger.info("Error : no se pudo copiar") time.sleep(1) if copy: if xbmc.Player().isPlayingVideo(): xbmc.executebuiltin("RunScript(script.xbmc.subtitles)") while xbmc.Player().isPlayingVideo(): continue time.sleep(1) os.remove(full_path_video_new) try: if full_path_tvshow != "": os.rmdir(full_path_tvshow) except OSError: pass
def bloque_enlaces(data, filtro_idioma, dict_idiomas, type, item): logger.info("pelisalacarta.channels.cinetux bloque_enlaces") lista_enlaces = [] matches = [] if type == "online": patron = '<a href="#([^"]+)" data-toggle="tab">([^<]+)</a>' bloques = scrapertools.find_multiple_matches(data, patron) for id, language in bloques: patron = 'id="' + id + '">.*?<iframe src="([^"]+)"' url = scrapertools.find_single_match(data, patron) matches.append([url, "", language]) bloque2 = scrapertools.find_single_match(data, '<div class="table-link" id="' + type + '">(.*?)</table>') patron = 'tr>[^<]+<td>.*?href="([^"]+)".*?src.*?title="([^"]+)"' \ '.*?src.*?title="([^"]+)".*?src.*?title="(.*?)"' matches.extend(scrapertools.find_multiple_matches(bloque2, patron)) filtrados = [] for match in matches: scrapedurl = match[0] language = match[2].strip() if match[1] == "": server = servertools.get_server_from_url(scrapedurl) title = " Mirror en " + server + " (" + language + ")" else: server = match[1].lower() if server == "uploaded": server = "uploadedto" elif server == "streamin": server = "streaminto" elif server == "netu": server = "netutv" mostrar_server = True if config.get_setting("hidepremium") == "true": mostrar_server = servertools.is_server_enabled(server) if mostrar_server: try: servers_module = __import__("servers." + server) except: pass title = " Mirror en " + server + " (" + language + ") (Calidad " + match[3].strip() + ")" if filtro_idioma == 3 or item.filtro: lista_enlaces.append(item.clone(title=title, action="play", server=server, text_color=color2, url=scrapedurl, idioma=language)) else: idioma = dict_idiomas[language] if idioma == filtro_idioma: lista_enlaces.append(item.clone(title=title, text_color=color2, action="play", url=scrapedurl, server=server)) else: if language not in filtrados: filtrados.append(language) if filtro_idioma != 3: if len(filtrados) > 0: title = "Mostrar enlaces filtrados en %s" % ", ".join(filtrados) lista_enlaces.append(item.clone(title=title, action="findvideos", url=item.url, text_color=color3, filtro=True)) return lista_enlaces
# -*- coding: utf-8 -*- import re import urllib import urlparse from core import config from core import jsontools from core import logger from core import scrapertools from core.item import Item host = "http://www.documaniatv.com/" account = config.get_setting("documaniatvaccount", "documaniatv") headers = [[ 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0' ], ['Referer', host]] def login(): logger.info() user = config.get_setting("documaniatvuser", "documaniatv") password = config.get_setting("documaniatvpassword", "documaniatv") if user == "" or password == "": return True, "" data = scrapertools.cachePage(host, headers=headers) if "http://www.documaniatv.com/user/" + user in data:
def login(): url = "http://www.torrentestrenos.com/index.php" post = "login="******"torrentestrenosuser")+"&password="******"torrentestrenospassword")+"&Submit=ENTRAR" data = scrapertools.cache_page(url,post=post)
# ------------------------------------------------------------ import os import re import unicodedata from threading import Thread from core import config from core import httptools from core import logger from core import scrapertools from core import servertools from core import tmdb from core.item import Item __modo_grafico__ = config.get_setting('modo_grafico', "ver-pelis") #Para la busqueda en bing evitando baneos def browser(url): import mechanize # Utilizamos Browser mechanize para saltar problemas con la busqueda en bing br = mechanize.Browser() # Browser options br.set_handle_equiv(False) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(False) br.set_handle_robots(False)
def getitems(item, requestpath): logger.info("getitems") itemlist = [] # Extrae los parámetros channel = item.channel accion = item.action url = item.url if url != "none": if not "filenium" in url: url = urllib.unquote_plus(url) server = item.server title = item.title extra = item.extra category = item.category fulltitle = item.fulltitle try: if accion == "mainlist" and config.get_setting( "updatechannels") == "true": try: logger.info("Verificando actualización del canal") from core import updater actualizado = updater.updatechannel(channel) if actualizado: itemlist.append( Item(title="¡Canal descargado y actualizado!")) except: import sys for line in sys.exc_info(): logger.error("%s" % line) logger.info("Not cached") # El item que invocó es importante para obtener el siguiente senderitem = Item(title=title, channel=channel, action=accion, url=url, server=server, extra=extra, category=category, fulltitle=fulltitle) if "|" in url: partes = urllib.unquote_plus(senderitem.url).split("|") refered_item = Item(title=partes[0], url=partes[2], thumbnail="", server=partes[1], plot="", extra=partes[3]) logger.info("refered_item title=" + refered_item.title + ", url=" + refered_item.url + ", server=" + refered_item.server + ", extra=" + refered_item.extra) else: refered_item = Item() # Importa el canal y ejecuta la función try: exec "from pelisalacarta.channels import " + channel + " as channelmodule" except: import sys for line in sys.exc_info(): logger.error("%s" % line) try: exec "from pelisalacarta import " + channel + " as channelmodule" except: import sys for line in sys.exc_info(): logger.error("%s" % line) try: exec "from core import " + channel + " as channelmodule" except: pass # play - es el menú de reproducción de un vídeo if accion == "play": logger.info("ACCION PLAY") if hasattr(channelmodule, 'play'): logger.info("[launcher.py] executing channel 'play' method") logger.info(channelmodule.__file__) itemlist = channelmodule.play(senderitem) logger.info("itemlist" + str(itemlist)) senderitem = itemlist[0] senderitem.folder = False else: logger.info( "[launcher.py] no channel 'play' method, executing core method" ) itemlist = menu_video(senderitem) # play_video - genera una playlist con una sola entrada para que wiimc la reproduzca elif accion == "play_video": logger.info("ACCION PLAY_VIDEO") logger.info("url=" + senderitem.url) senderitem.folder = False itemlist.append(senderitem) # search - es el buscador elif channel == "buscador" and accion == "mainlist": logger.info("ACCION SEARCH (buscador)") texto = requestpath.split("plx")[1] exec "itemlist = buscador.do_search_results(texto)" elif accion == "search": logger.info("ACCION SEARCH") texto = requestpath.split("plx")[1] exec "itemlist = channelmodule." + accion + "(senderitem,texto)" elif accion == "login": logger.info("ACCION LOGIN") user = requestpath.split("plx")[1] itemlist.append( Item(channel=item.channel, title="Contraseña", action="password", url=item.url, extra=user)) elif accion == "password": logger.info("ACCION LOGIN") user = item.extra password = requestpath.split("plx")[1] login = user + "|" + password senderitem = Item(title=title, channel=channel, action=accion, url=url, server=server, extra=login, category=category, fulltitle=fulltitle) exec "itemlist = channelmodule.login(senderitem)" # findvideos - debe encontrar videos reproducibles elif accion == "findvideos": logger.info("ACCION FINDVIDEOS") try: exec "itemlist = channelmodule." + accion + "(senderitem)" except: import sys for line in sys.exc_info(): logger.error("%s" % line) itemlist = findvideos(senderitem, channel) elif accion == "descargar": itemlist = download_item(senderitem, refered_item) elif accion == "download_all": itemlist = download_all(senderitem, refered_item) elif accion == "add_to_favorites": itemlist = add_to_favorites(senderitem, refered_item) elif accion == "remove_from_favorites": itemlist = remove_from_favorites(senderitem, refered_item) elif accion == "add_to_downloads": itemlist = add_to_downloads(senderitem, refered_item) elif accion == "remove_from_downloads": itemlist = remove_from_downloads(senderitem, refered_item) elif accion == "remove_from_error_downloads": itemlist = remove_from_error_downloads(senderitem, refered_item) elif accion == "add_again_to_downloads": itemlist = add_again_to_downloads(senderitem, refered_item) elif accion == "send_to_jdownloader": itemlist = send_to_jdownloader(senderitem, refered_item) elif accion == "search_trailer": itemlist = search_trailer(senderitem, refered_item) elif accion == "add_serie_to_wiideoteca": itemlist = wiideoteca.AgregarSerie(senderitem) elif accion == "UltimoVisto": itemlist = wiideoteca.UltimoVisto(senderitem) else: if senderitem.url == "none": senderitem.url = "" exec "itemlist.extend( channelmodule." + accion + "(senderitem) )" ''' # Lo almacena en cache fichero = open( cached_file ,"wb") cerealizer.dump(itemlist,fichero) fichero.close() ''' logger.info("Items devueltos ") for item in itemlist: logger.info(" " + item.title + " | " + item.url + " | " + item.action) except: import traceback, sys from pprint import pprint exc_type, exc_value, exc_tb = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_tb) for line in lines: line_splits = line.split("\n") for line_split in line_splits: logger.error(line_split) return itemlist, channel
def mainlist(item): logger.info() itemlist = [] item.text_color = color1 proxy_usa = config.get_setting("proxy_usa", "crunchyroll") proxy_spain = config.get_setting("proxy_spain", "crunchyroll") item.login = False error_message = "" global host if not proxy_usa and not proxy_spain: item.login, error_message, premium = login() elif proxy_usa: item.proxy = "usa" host = proxy_u + host elif proxy_spain: httptools.downloadpage("http://proxyanonimo.es/") item.proxy = "spain" host = proxy_e + host if not item.login and error_message: itemlist.append( item.clone(title=error_message, action="configuracion", folder=False, text_color=color4)) elif item.login: itemlist.append( item.clone(title="Tipo de cuenta: %s" % premium, action="", text_color=color4)) elif item.proxy: itemlist.append( item.clone(title="Usando proxy: %s" % item.proxy.capitalize(), action="", text_color=color4)) itemlist.append(item.clone(title="Anime", action="", text_color=color2)) item.contentType = "tvshow" itemlist.append( item.clone(title=" Novedades", action="lista", url=host + "/videos/anime/updated/ajax_page?pg=0", page=0)) itemlist.append( item.clone(title=" Popular", action="lista", url=host + "/videos/anime/popular/ajax_page?pg=0", page=0)) itemlist.append( item.clone(title=" Emisiones Simultáneas", action="lista", url=host + "/videos/anime/simulcasts/ajax_page?pg=0", page=0)) itemlist.append(item.clone(title=" Índices", action="indices")) itemlist.append(item.clone(title="Drama", action="", text_color=color2)) itemlist.append( item.clone(title=" Popular", action="lista", url=host + "/videos/drama/popular/ajax_page?pg=0", page=0)) itemlist.append( item.clone(title=" Índice Alfabético", action="indices", url="http://www.crunchyroll.com/videos/drama/alpha")) if item.proxy != "usa": itemlist.append( item.clone(action="calendario", title="Calendario de Estrenos Anime", text_color=color4, url=host + "/simulcastcalendar")) itemlist.append( item.clone(title="Configuración del canal", action="configuracion", text_color="gold")) return itemlist
def get_video_url(page_url, premium=False, user="", password="", video_password=""): logger.info("url=" + page_url) video_urls = [] if "crunchyroll.com" in page_url: media_id = page_url.rsplit("-", 1)[1] else: media_id = scrapertools.find_single_match(page_url, 'media_id=(\d+)') url = "http://www.crunchyroll.com/xml/?req=RpcApiVideoPlayer_GetStandardConfig&media_id=%s" \ "&video_format=0&video_quality=0&auto_play=0&aff=af-12299-plwa" % media_id post = "current_page=%s" % page_url data = httptools.downloadpage(url, post, headers=GLOBAL_HEADER, replace_headers=True).data if "<msg>Media not available</msg>" in data or "flash_block.png" in data: data = httptools.downloadpage(proxy + url, post, headers=GLOBAL_HEADER, replace_headers=True, cookies=False).data media_url = scrapertools.find_single_match(data, '<file>(.*?)</file>').replace( "&", "&") if not media_url: return video_urls elif not media_url.startswith("http"): rtmp = scrapertools.find_single_match(data, '<host>(.*?)</host>').replace( "&", "&") media_url = rtmp + " playpath=%s" % media_url filename = "RTMP" else: filename = scrapertools.get_filename_from_url(media_url)[-4:] quality = scrapertools.find_single_match(data, '<height>(.*?)</height>') try: idiomas = [ 'Español \(España\)', 'Español\]', 'English', 'Italiano', 'Français', 'Português', 'Deutsch' ] index_sub = int(config.get_setting("sub", server="crunchyroll")) idioma_sub = idiomas[index_sub] link_sub = scrapertools.find_single_match( data, "link='([^']+)' title='\[%s" % idioma_sub) if not link_sub and index_sub == 0: link_sub = scrapertools.find_single_match( data, "link='([^']+)' title='\[Español\]") elif not link_sub and index_sub == 1: link_sub = scrapertools.find_single_match( data, "link='([^']+)' title='\[Español \(España\)") if not link_sub: link_sub = scrapertools.find_single_match( data, "link='([^']+)' title='\[English") data_sub = httptools.downloadpage(link_sub.replace("&", "&"), headers=GLOBAL_HEADER, replace_headers=True).data id_sub = scrapertools.find_single_match(data_sub, "subtitle id='([^']+)'") iv = scrapertools.find_single_match(data_sub, '<iv>(.*?)</iv>') data_sub = scrapertools.find_single_match(data_sub, '<data>(.*?)</data>') file_sub = decrypt_subs(iv, data_sub, id_sub) except: import traceback logger.error(traceback.format_exc()) file_sub = "" video_urls.append([ "%s %sp [crunchyroll]" % (filename, quality), media_url, 0, file_sub ]) for video_url in video_urls: logger.info("%s - %s" % (video_url[0], video_url[1])) return video_urls
try: self.ID = "%032x" % (random.getrandbits(128)) from platformcode.controllers.html import html self.controller = html(self, self.ID) self.server.fnc_info() except: logger.error(traceback.format_exc()) self.close() def handleClose(self): self.controller.__del__() del self.controller self.server.fnc_info() port = config.get_setting("websocket.port") server = WebSocketServer.SimpleWebSocketServer("", int(port), HandleWebSocket) def start(fnc_info): server.fnc_info = fnc_info Thread(target=server.serveforever).start() def stop(): server.close() def run(controller, path): try: controller.run(path)
import re import urllib import urlparse from core import config from core import httptools from core import jsontools from core import logger from core import scrapertools from core import servertools from core.item import Item from platformcode import platformtools host = "http://hdfull.tv" if config.get_setting('hdfulluser', 'hdfull'): account = True else: account = False def settingCanal(item): return platformtools.show_channel_settings() def login(): logger.info() data = agrupa_datos(httptools.downloadpage(host).data) patron = "<input type='hidden' name='__csrf_magic' value=\"([^\"]+)\" />"
def findvideos(item): logger.info() # logger.debug("item:\n" + item.tostring('\n')) itemlist = [] list_canales = {} item_local = None if not item.contentTitle or not item.strm_path: logger.debug("No se pueden buscar videos por falta de parametros") return [] content_title = filter(lambda c: c not in ":*?<>|\/", item.contentTitle).strip().lower() if item.contentType == 'movie': item.strm_path = filetools.join(library.MOVIES_PATH, item.strm_path) path_dir = os.path.dirname(item.strm_path) item.nfo = filetools.join(path_dir, os.path.basename(path_dir) + ".nfo") else: item.strm_path = filetools.join(library.TVSHOWS_PATH, item.strm_path) path_dir = os.path.dirname(item.strm_path) item.nfo = filetools.join(path_dir, 'tvshow.nfo') for fd in filetools.listdir(path_dir): if fd.endswith('.json'): contenido, nom_canal = fd[:-6].split('[') if (contenido.startswith(content_title) or item.contentType == 'movie') and nom_canal not in \ list_canales.keys(): list_canales[nom_canal] = filetools.join(path_dir, fd) num_canales = len(list_canales) # logger.debug(str(list_canales)) if 'descargas' in list_canales: json_path = list_canales['descargas'] item_json = Item().fromjson(filetools.read(json_path)) item_json.contentChannel = "local" # Soporte para rutas relativas en descargas if filetools.is_relative(item_json.url): item_json.url = filetools.join(library.LIBRARY_PATH, item_json.url) del list_canales['descargas'] # Comprobar q el video no haya sido borrado if filetools.exists(item_json.url): item_local = item_json.clone(action='play') itemlist.append(item_local) else: num_canales -= 1 filtro_canal = '' if num_canales > 1 and config.get_setting("ask_channel", "biblioteca") == True: opciones = [ "Mostra solo link %s" % k.capitalize() for k in list_canales.keys() ] opciones.insert(0, "Mosta tutti i collegamenti") if item_local: opciones.append(item_local.title) from platformcode import platformtools index = platformtools.dialog_select(config.get_localized_string(30163), opciones) if index < 0: return [] elif item_local and index == len(opciones) - 1: filtro_canal = 'descargas' platformtools.play_video(item_local) elif index > 0: filtro_canal = opciones[index].replace("Mostra solo link ", "") itemlist = [] for nom_canal, json_path in list_canales.items(): if filtro_canal and filtro_canal != nom_canal.capitalize(): continue # Importamos el canal de la parte seleccionada try: channel = __import__('channels.%s' % nom_canal, fromlist=["channels.%s" % nom_canal]) except ImportError: exec "import channels." + nom_canal + " as channel" item_json = Item().fromjson(filetools.read(json_path)) list_servers = [] try: # FILTERTOOLS # si el canal tiene filtro se le pasa el nombre que tiene guardado para que filtre correctamente. if "list_idiomas" in item_json: # si se viene desde la biblioteca de pelisalacarta if "library_filter_show" in item: item_json.show = item.library_filter_show.get( nom_canal, "") # Ejecutamos find_videos, del canal o común if hasattr(channel, 'findvideos'): list_servers = getattr(channel, 'findvideos')(item_json) else: from core import servertools list_servers = servertools.find_video_items(item_json) except Exception as ex: logger.error("Ha fallado la funcion findvideos para el canal %s" % nom_canal) template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) logger.error(message) # Cambiarle el titulo a los servers añadiendoles el nombre del canal delante y # las infoLabels y las imagenes del item si el server no tiene for server in list_servers: if not server.action: # Ignorar las etiquetas continue server.contentChannel = server.channel server.channel = "biblioteca" server.nfo = item.nfo server.strm_path = item.strm_path # Se añade el nombre del canal si se desea if config.get_setting("quit_channel_name", "biblioteca") == 0: server.title = "%s: %s" % (nom_canal.capitalize(), server.title) server.infoLabels = item_json.infoLabels if not server.thumbnail: server.thumbnail = item.thumbnail # logger.debug("server:\n%s" % server.tostring('\n')) itemlist.append(server) # return sorted(itemlist, key=lambda it: it.title.lower()) return itemlist
def onInit(self): self.getControl(10004).setEnabled(False) self.getControl(10005).setEnabled(False) self.getControl(10006).setEnabled(False) self.ok_enabled = False self.default_enabled = False if xbmcgui.__version__ == "1.2": self.setCoordinateResolution(1) else: self.setCoordinateResolution(5) # Ponemos el título self.getControl(10002).setLabel(self.title) if self.custom_button is not None: if self.custom_button['visible']: self.getControl(10006).setLabel(self.custom_button['label']) else: self.getControl(10006).setVisible(False) self.getControl(10004).setPosition( self.getControl(10004).getPosition()[0] + 80, self.getControl(10004).getPosition()[1]) self.getControl(10005).setPosition( self.getControl(10005).getPosition()[0] + 80, self.getControl(10005).getPosition()[1]) # Obtenemos las dimensiones del area de controles self.controls_width = self.getControl(10007).getWidth() - 20 self.controls_height = self.getControl(10007).getHeight() self.controls_pos_x = self.getControl(10007).getPosition( )[0] + self.getControl(10001).getPosition()[0] + 10 self.controls_pos_y = self.getControl( 10007).getPosition()[1] + self.getControl(10001).getPosition()[1] self.height_control = 35 self.font = "font12" # En versiones antiguas: creamos 5 controles, de lo conrtario al hacer click al segundo control, # automaticamente cambia el label del tercero a "Short By: Name" no se porque... if xbmcgui.ControlEdit == ControlEdit: for x in range(5): control = xbmcgui.ControlRadioButton(-500, 0, 0, 0, "") self.addControl(control) for c in self.list_controls: # Saltamos controles que no tengan los valores adecuados if "type" not in c: continue if "label" not in c: continue if c["type"] != "label" and "id" not in c: continue if c["type"] == "list" and "lvalues" not in c: continue if c["type"] == "list" and not type(c["lvalues"]) == list: continue if c["type"] == "list" and not len(c["lvalues"]) > 0: continue if c["type"] != "label" and len([ control.get("id") for control in self.list_controls if c["id"] == control.get("id") ]) > 1: continue # Translation label y lvalues if c['label'].startswith('@') and unicode( c['label'][1:]).isnumeric(): c['label'] = config.get_localized_string(int(c['label'][1:])) if c['type'] == 'list': lvalues = [] for li in c['lvalues']: if li.startswith('@') and unicode(li[1:]).isnumeric(): lvalues.append(config.get_localized_string(int( li[1:]))) else: lvalues.append(li) c['lvalues'] = lvalues # Valores por defecto en caso de que el control no disponga de ellos if c["type"] == "bool" and "default" not in c: c["default"] = False if c["type"] == "text" and "default" not in c: c["default"] = "" if c["type"] == "text" and "hidden" not in c: c["hidden"] = False if c["type"] == "list" and "default" not in c: c["default"] = 0 if c["type"] == "label" and "id" not in c: c["id"] = None if "color" not in c: c["color"] = "0xFF0066CC" if "visible" not in c: c["visible"] = True if "enabled" not in c: c["enabled"] = True if c["type"] == "text" and not type(c["hidden"]) == bool: if c["hidden"].lower() == 'true': c["hidden"] = True else: c["hidden"] = False # Decidimos si usar el valor por defecto o el valor guardado if c["type"] in ["bool", "text", "list"]: if id not in self.values: if not self.callback: self.values[c["id"]] = config.get_setting( c["id"], self.channel) else: self.values[c["id"]] = c["default"] if c["type"] == "bool": c["default"] = bool(c["default"]) self.values[c["id"]] = bool(self.values[c["id"]]) if c["type"] == "bool": self.add_control_bool(c) elif c["type"] == 'text': self.add_control_text(c) elif c["type"] == 'list': self.add_control_list(c) elif c["type"] == 'label': self.add_control_label(c) self.list_controls = [c for c in self.list_controls if "control" in c] self.evaluate_conditions() self.index = -1 self.dispose_controls(0) self.getControl(100010).setVisible(False) self.getControl(10004).setEnabled(True) self.getControl(10005).setEnabled(True) self.getControl(10006).setEnabled(True) self.ok_enabled = True self.default_enabled = True self.check_default() self.check_ok(self.values)
def findvideos(item): logger.info() itemlist = [] ## Carga estados status = jsontools.load( httptools.downloadpage(host + '/a/status/all').data) url_targets = item.url ## Vídeos if "###" in item.url: id = item.url.split("###")[1].split(";")[0] type = item.url.split("###")[1].split(";")[1] item.url = item.url.split("###")[0] if type == "2" and account and item.category != "Cine": title = bbcode_kodi2html( " ( [COLOR orange][B]Agregar a Favoritos[/B][/COLOR] )") if "Favorito" in item.title: title = bbcode_kodi2html( " ( [COLOR red][B]Quitar de Favoritos[/B][/COLOR] )") if config.get_videolibrary_support(): title_label = bbcode_kodi2html(" ( [COLOR gray][B]" + item.show + "[/B][/COLOR] )") itemlist.append( Item(channel=item.channel, action="findvideos", title=title_label, fulltitle=title_label, url=url_targets, thumbnail=item.thumbnail, show=item.show, folder=False)) title_label = bbcode_kodi2html( " ( [COLOR green][B]Tráiler[/B][/COLOR] )") itemlist.append( Item(channel=item.channel, action="trailer", title=title_label, fulltitle=title_label, url=url_targets, thumbnail=item.thumbnail, show=item.show)) itemlist.append( Item(channel=item.channel, action="set_status", title=title, fulltitle=title, url=url_targets, thumbnail=item.thumbnail, show=item.show, folder=True)) data_js = httptools.downloadpage( "http://hdfull.tv/templates/hdfull/js/jquery.hdfull.view.min.js").data key = scrapertools.find_single_match( data_js, 'JSON.parse\(atob.*?substrings\((.*?)\)') data_js = httptools.downloadpage("http://hdfull.tv/js/providers.js").data try: data_js = jhexdecode(data_js) except: from lib.aadecode import decode as aadecode data_js = data_js.split(";゚ω゚") decode_aa = "" for match in data_js: decode_aa += aadecode(match) data_js = re.sub(r':(function.*?\})', r':"\g<1>"', decode_aa) data_js = re.sub(r':(var[^,]+),', r':"\g<1>",', data_js) data = agrupa_datos(httptools.downloadpage(item.url).data) data_obf = scrapertools.find_single_match(data, "var ad\s*=\s*'([^']+)'") data_decrypt = jsontools.load( obfs(base64.b64decode(data_obf), 126 - int(key))) infolabels = {} year = scrapertools.find_single_match( data, '<span>Año:\s*</span>.*?(\d{4})') infolabels["year"] = year matches = [] for match in data_decrypt: prov = eval( scrapertools.find_single_match( data_js, 'p\[%s\]\s*=\s*(\{.*?\}[\'"]\})' % match["provider"])) function = prov["l"].replace("code", match["code"]).replace( "var_1", match["code"]) url = scrapertools.find_single_match(function, "return\s*(.*?)[;]*\}") url = re.sub(r'\'|"|\s|\+', '', url) url = re.sub(r'var_\d+\[\d+\]', '', url) embed = prov["e"] matches.append([match["lang"], match["quality"], url, embed]) enlaces = [] for idioma, calidad, url, embed in matches: servername = scrapertools.find_single_match( url, "(?:http:|https:)//(?:www.|)([^.]+).") if servername == "streamin": servername = "streaminto" if servername == "waaw": servername = "netutv" if servername == "uploaded" or servername == "ul": servername = "uploadedto" mostrar_server = True if config.get_setting("hidepremium") == True: mostrar_server = servertools.is_server_enabled(servername) if mostrar_server: option = "Ver" if re.search(r'return ([\'"]{2,}|\})', embed): option = "Descargar" calidad = unicode(calidad, "utf8").upper().encode("utf8") servername_c = unicode(servername, "utf8").capitalize().encode("utf8") title = option + ": " + servername_c + " (" + calidad + ")" + " (" + idioma + ")" thumbnail = item.thumbnail plot = item.title + "\n\n" + scrapertools.find_single_match( data, '<meta property="og:description" content="([^"]+)"') plot = scrapertools.htmlclean(plot) fanart = scrapertools.find_single_match( data, '<div style="background-image.url. ([^\s]+)') if account: url += "###" + id + ";" + type enlaces.append( Item(channel=item.channel, action="play", title=title, fulltitle=title, url=url, thumbnail=thumbnail, plot=plot, fanart=fanart, show=item.show, folder=True, server=servername, infoLabels=infolabels, contentTitle=item.contentTitle, contentType=item.contentType, tipo=option)) enlaces.sort(key=lambda it: it.tipo, reverse=True) itemlist.extend(enlaces) ## 2 = película if type == "2" and item.category != "Cine": ## STRM para todos los enlaces de servidores disponibles ## Si no existe el archivo STRM de la peícula muestra el item ">> Añadir a la videoteca..." try: itemlist.extend(file_cine_library(item, url_targets)) except: pass return itemlist
def login(): url = "http://series.mu/login/" post = "user="******"seriesmuuser")+"&pass="******"seriesmupassword") data = scrapertools.cache_page(url,post=post)
import re import urllib2 from core import config from core import jsontools from core import logger from core import scrapertools from core.item import InfoLabels from platformcode import platformtools HOST = "https://api.thetvdb.com" HOST_IMAGE = "http://thetvdb.com/banners/" # comprobación tras el cambio de tipos en config.get_setting if config.get_setting("tvdb_token") is not None: TOKEN = config.get_setting("tvdb_token") else: TOKEN = "" DEFAULT_LANG = "es" DEFAULT_HEADERS = { 'Content-Type': 'application/json', 'Accept': 'application/json, application/vnd.thetvdb.v2.1.1', 'Accept-Language': DEFAULT_LANG, 'Authorization': 'Bearer ' + TOKEN, } # Traducciones - Inicio DICT_STATUS = {'Continuing': 'En emisión', 'Ended': 'Finalizada'} DICT_GENRE = {