def CreateIndex(IndexPath, Folder): import hashlib logger.info("Creando indice de: " + Folder) JSONData={} for File in os.listdir(os.path.join(config.get_runtime_path(), Folder)): File = os.path.join(config.get_runtime_path(), Folder,File) if not File.endswith(".pyc"): FileData = open(File, 'rb').read() JSONFile={} JSONFile["sha"] = [] JSONFile["sha"].append(hashlib.sha1("blob " + str(len(FileData)) + "\0" + FileData).hexdigest()) JSONFile["sha"].append(str(len(FileData))) FileData = FileData.replace("\r\n", "\n") FileData = FileData.replace("\r", "\n") JSONFile["sha"].append(hashlib.sha1("blob " + str(len(FileData)) + "\0" + FileData).hexdigest()) JSONFile["sha"].append(str(len(FileData))) FileData = FileData.replace("\n", "\r") JSONFile["sha"].append(hashlib.sha1("blob " + str(len(FileData)) + "\0" + FileData).hexdigest()) JSONFile["sha"].append(str(len(FileData))) FileData = FileData.replace("\r", "\r\n") JSONFile["sha"].append(hashlib.sha1("blob " + str(len(FileData)) + "\0" + FileData).hexdigest()) JSONFile["sha"].append(str(len(FileData))) JSONData[os.path.basename(File)] = JSONFile open(IndexPath,"w").write(json.dumps(JSONData, indent=4, sort_keys=True))
def PostItem(item, itemlist): for x in range(len(itemlist)): #Menu Contextual "Favoritos" if itemlist[x].context: context = itemlist[x].context.split("|") else: context=[] if not item.channel in ["channelselector","favoritos","buscador","descargas","biblioteca", "novedades"] or item.channel =="channelselector" and item.action =="listchannels": context.append("Añadir a Favoritos,add_to_favorites") if itemlist[x].action == "play" and not itemlist[x].channel =="descargas": context.append("Descargar,download") itemlist[x].context= "|".join(context) #Icono Search if itemlist[x].thumbnail =="" and itemlist[x].action =="search": itemlist[x].thumbnail="%s/search.png" if itemlist[x].fanart=="": channel_fanart = os.path.join( config.get_runtime_path(), 'resources', 'images', 'fanart', itemlist[x].channel+'.jpg') if os.path.exists(channel_fanart): itemlist[x].fanart = channel_fanart else: itemlist[x].fanart = os.path.join(config.get_runtime_path(),"fanart.jpg") return itemlist
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 CreateIndex(IndexPath, Folder): import hashlib logger.info("Creando indice de: " + Folder) JSONData=[] for File in os.listdir(os.path.join(config.get_runtime_path(), Folder)): File = os.path.join(config.get_runtime_path(), Folder,File) if not File.endswith(".pyc"): FileData = open(File, 'rb').read() FileData = FileData.replace("\r\n", "\n") FileData = FileData.replace("\r", "\n") JSONFile={} JSONFile["name"] = os.path.basename(File) JSONFile["size"] = len(FileData) JSONFile["path"] = "python/main-classic/"+Folder + "/" + JSONFile["name"] JSONFile["url"] = "https://api.github.com/repos/"+repo+"/contents/" + JSONFile["path"] + "?ref=master" JSONFile["type"] = "file" JSONFile["sha"] = hashlib.sha1("blob " + str(JSONFile["size"]) + "\0" + FileData).hexdigest() JSONFile["download_url"] = "https://raw.githubusercontent.com/"+repo+"/master/" + JSONFile["path"] JSONFile["git_url"] = "https://api.github.com/repos/"+repo+"/git/blobs/" + JSONFile["sha"] JSONFile["html_url"] = "https://github.com/"+repo+"/blob/master/"+ JSONFile["path"] JSONFile["_links"]={} JSONFile["_links"]["git"] = JSONFile["git_url"] JSONFile["_links"]["html"] = JSONFile["html_url"] JSONFile["_links"]["self"] = JSONFile["url"] JSONData.append(JSONFile) JSONData.sort(key=lambda item: item["name"]) open(IndexPath,"w").write(json.dumps(JSONData, indent=4, sort_keys=True))
def renderItems(itemlist, params, url, category,isPlayable='false'): viewmode = "list" if itemlist <> None: for item in itemlist: #logger.info("renderItems item="+item.title+", media_url="+item.media_url) if item.category == "": item.category = category if item.fulltitle=="": item.fulltitle=item.title if item.fanart=="": channel_fanart = os.path.join( config.get_runtime_path(), 'resources', 'images', 'fanart', item.channel+'.jpg') if os.path.exists(channel_fanart): item.fanart = channel_fanart else: item.fanart = os.path.join(config.get_runtime_path(),"fanart.jpg") if item.folder : add_new_folder( item , totalItems=len(itemlist) ) else: if config.get_setting("player_mode")=="1": # SetResolvedUrl debe ser siempre "isPlayable = true" isPlayable = "true" if item.duration: addnewvideo( item.channel , item.action , item.category , item.server, item.title , item.url , item.media_url , item.thumbnail , item.plot , item.uid, "" , duration = item.duration , fanart = item.fanart, IsPlayable=isPlayable,context = item.context , subtitle=item.subtitle, totalItems = len(itemlist), show=item.show, password = item.password, extra = item.extra, fulltitle=item.fulltitle, size=item.size ) else: addnewvideo( item.channel , item.action , item.category , item.server, item.title , item.url , item.media_url , item.thumbnail , item.plot, item.uid, fanart = item.fanart, IsPlayable=isPlayable , context = item.context , subtitle = item.subtitle , totalItems = len(itemlist), show=item.show , password = item.password , extra=item.extra, fulltitle=item.fulltitle, size=item.size ) if item.viewmode!="list": viewmode = item.viewmode # Cierra el directorio xbmcplugin.setPluginCategory( handle=pluginhandle, category=category ) xbmcplugin.addSortMethod( handle=pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_NONE ) if config.get_setting("forceview")=="true": if viewmode=="list": xbmcplugin.setContent(pluginhandle,"Movies") xbmc.executebuiltin("Container.SetViewMode(50)") elif viewmode=="movie_with_plot": xbmcplugin.setContent(pluginhandle,"Movies") xbmc.executebuiltin("Container.SetViewMode(504)") elif viewmode=="movie": xbmcplugin.setContent(pluginhandle,"Movies") xbmc.executebuiltin("Container.SetViewMode(500)") elif viewmode=="series": xbmcplugin.setContent(pluginhandle,"tvshows") xbmc.executebuiltin("Container.SetViewMode(504)") elif viewmode=="episodes": xbmcplugin.setContent(pluginhandle,"episodes") xbmc.executebuiltin("Container.SetViewMode(504)") xbmcplugin.endOfDirectory( handle=pluginhandle, succeeded=True )
def renderItems(itemlist, params, url, category, isPlayable='false'): viewmode = "list" if itemlist <> None: for item in itemlist: logger.info("item="+item.tostring()) if item.category == "": item.category = category if item.fulltitle=="": item.fulltitle=item.title if item.fanart=="": channel_fanart = os.path.join( config.get_runtime_path(), 'resources', 'images', 'fanart', item.channel+'.jpg') if os.path.exists(channel_fanart): item.fanart = channel_fanart else: item.fanart = os.path.join(config.get_runtime_path(),"fanart.jpg") if item.folder: addnewfolderextra( item.channel , item.action , item.category , item.title , item.url , item.thumbnail , item.plot , extradata = item.extra , totalItems = len(itemlist), fanart=item.fanart , context=item.context, show=item.show, fulltitle=item.fulltitle, hasContentDetails=item.hasContentDetails, contentTitle=item.contentTitle, contentThumbnail=item.contentThumbnail, contentPlot=item.contentPlot ) else: if config.get_setting("player_mode")=="1": # SetResolvedUrl debe ser siempre "isPlayable = true" isPlayable = "true" if item.duration: addnewvideo( item.channel , item.action , item.category , item.server, item.title , item.url , item.thumbnail , item.plot , "" , duration = item.duration , fanart = item.fanart, IsPlayable=isPlayable,context = item.context , subtitle=item.subtitle, totalItems = len(itemlist), show=item.show, password = item.password, extra = item.extra, fulltitle=item.fulltitle, hasContentDetails=item.hasContentDetails, contentTitle=item.contentTitle, contentThumbnail=item.contentThumbnail, contentPlot=item.contentPlot ) else: addnewvideo( item.channel , item.action , item.category , item.server, item.title , item.url , item.thumbnail , item.plot, fanart = item.fanart, IsPlayable=isPlayable , context = item.context , subtitle = item.subtitle , totalItems = len(itemlist), show=item.show , password = item.password , extra=item.extra, fulltitle=item.fulltitle, hasContentDetails=item.hasContentDetails, contentTitle=item.contentTitle, contentThumbnail=item.contentThumbnail, contentPlot=item.contentPlot ) if item.viewmode!="list": viewmode = item.viewmode # Cierra el directorio xbmcplugin.setContent(pluginhandle,"Movies") xbmcplugin.setPluginCategory( handle=pluginhandle, category=category ) xbmcplugin.addSortMethod( handle=pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_NONE ) # Modos biblioteca # MediaInfo3 - 503 # # Modos fichero # WideIconView - 505 # ThumbnailView - 500 if config.get_setting("forceview")=="true": if viewmode=="list": xbmc.executebuiltin("Container.SetViewMode(50)") elif viewmode=="movie_with_plot": xbmc.executebuiltin("Container.SetViewMode(503)") elif viewmode=="movie": xbmc.executebuiltin("Container.SetViewMode(500)") xbmcplugin.endOfDirectory( handle=pluginhandle, succeeded=True )
def render_items(self, itemlist, parentitem): from core.item import Item if (parentitem.channel=="channelselector" and parentitem.action=="mainlist") or (parentitem.channel=="novedades" and parentitem.action=="mainlist") or (parentitem.channel=="buscador" and parentitem.action=="mainlist") or (parentitem.channel=="channelselector" and parentitem.action=="channeltypes"): viewmode = 0 elif parentitem.channel=="channelselector" and parentitem.action=="listchannels": viewmode = 1 else: viewmode = 2 if not (parentitem.channel=="channelselector" and parentitem.action=="mainlist") and not itemlist[0].action=="go_back": if viewmode !=2: itemlist.insert(0,Item(title="Atrás", action="go_back",thumbnail=os.path.join(config.get_runtime_path(),"resources","images","bannermenu","thumb_atras.png"))) else: itemlist.insert(0,Item(title="Atrás", action="go_back",thumbnail=os.path.join(config.get_runtime_path(),"resources","images","squares","thumb_atras.png"))) for item in itemlist: if item.thumbnail == "" and item.action == "search": item.thumbnail = config.get_thumbnail_path() + "thumb_buscar.png" if item.thumbnail == "" and item.folder == True: item.thumbnail = "http://media.tvalacarta.info/pelisalacarta/thumb_folder.png" if item.thumbnail == "" and item.folder == False: item.thumbnail = "http://media.tvalacarta.info/pelisalacarta/thumb_nofolder.png" if "http://media.tvalacarta.info/" in item.thumbnail and not item.thumbnail.startswith("http://media.tvalacarta.info/pelisalacarta/thumb_"): if viewmode != 2: item.thumbnail = config.get_thumbnail_path("bannermenu") + os.path.basename(item.thumbnail) else: item.thumbnail = config.get_thumbnail_path() + os.path.basename(item.thumbnail) #Estas imagenes no estan en bannermenu, asi que si queremos bannermenu, para que no se vean mal las quitamos elif viewmode != 2 and item.thumbnail.startswith("http://media.tvalacarta.info/pelisalacarta/thumb_"): item.thumbnail = "" if item.fanart == "": channel_fanart = os.path.join(config.get_runtime_path(), 'resources', 'images', 'fanart', item.channel + '.jpg') if os.path.exists(channel_fanart): item.fanart = channel_fanart else: item.fanart = os.path.join(config.get_runtime_path(), "fanart.jpg") if item.category == "": item.category = parentitem.category if item.fulltitle == "": item.fulltitle = item.title self.AddNewItem(item, totalItems=len(itemlist)) JsonData = {} JsonData["action"]="EndItems" JsonData["data"]={} JsonData["data"]["itemlist"]=self.item_list JsonData["data"]["mode"]=viewmode JsonData["data"]["host"]=self.controller.host ID = self.send_message(JsonData) self.item_list= [] while self.get_data(ID) == None: continue
def start(self, list_controls=None, dict_values=None, title="Opciones", callback=None, item=None, custom_button=None, channelpath = None): logger.info("[xbmc_config_menu] start") # Ruta para las imagenes de la ventana self.mediapath = os.path.join(config.get_runtime_path(), 'resources', 'skins', 'Default', 'media') # Capturamos los parametros self.list_controls = list_controls self.values = dict_values self.title = title self.callback = callback self.item = item if type(custom_button) == dict: self.custom_button = {} self.custom_button["label"] = custom_button.get("label", "") self.custom_button["function"] = custom_button.get("function", "") self.custom_button["visible"] = bool(custom_button.get("visible", True)) self.custom_button["close"] = bool(custom_button.get("close", False)) else: self.custom_button = None # Obtenemos el canal desde donde se ha echo la llamada y cargamos los settings disponibles para ese canal if not channelpath: channelpath = inspect.currentframe().f_back.f_back.f_code.co_filename self.channel = os.path.basename(channelpath).replace(".py", "") # Si no tenemos list_controls, hay que sacarlos del xml del canal if not self.list_controls: # Si la ruta del canal esta en la carpeta "channels", obtenemos los controles y valores mediante chaneltools if os.path.join(config.get_runtime_path(), "channels") in channelpath: # La llamada se hace desde un canal self.list_controls, default_values = channeltools.get_channel_controls_settings(self.channel) # En caso contrario salimos else: return None # Si no se pasan dict_values, creamos un dict en blanco if self.values is None: self.values = {} # Ponemos el titulo if self.title == "": self.title = str(config.get_localized_string(30100)) + " -- " + self.channel.capitalize() elif self.title.startswith('@') and unicode(self.title[1:]).isnumeric(): self.title = config.get_localized_string(int(self.title[1:])) # Muestra la ventana self.return_value = None self.doModal() return self.return_value
def ImportarCanal(channel): channelmodule="" if os.path.exists(os.path.join( config.get_runtime_path(), "channels",channel+".py")): exec "from channels import "+channel+" as channelmodule" elif os.path.exists(os.path.join( config.get_runtime_path(),"core",channel+".py")): exec "from core import "+channel+" as channelmodule" elif os.path.exists(os.path.join( config.get_runtime_path(),channel+".py")): exec "import "+channel+" as channelmodule" return channelmodule
def get_server_local_path(server_name): local_server_path = os.path.join(config.get_runtime_path(), 'servers', server_name + ".py") local_version_path = os.path.join(config.get_runtime_path(), 'servers', server_name + ".xml") local_compiled_path = os.path.join(config.get_runtime_path(), 'servers', server_name + ".pyo") logger.info("streamondemand.core.servertools local_servers_path=" + local_server_path) logger.info("streamondemand.core.servertools local_version_path=" + local_version_path) logger.info("streamondemand.core.servertools local_compiled_path=" + local_compiled_path) return local_server_path, local_version_path, local_compiled_path
def renderItems(itemlist, params, url, category,isPlayable='false'): viewmode = -1 if itemlist <> None: for item in itemlist: if item.category == "": item.category = category if item.fulltitle=="": item.fulltitle=item.title if item.fanart=="": channel_fanart = os.path.join( config.get_runtime_path(), 'resources', 'images', 'fanart', item.channel+'.jpg') if os.path.exists(channel_fanart): item.fanart = channel_fanart else: item.fanart = os.path.join(config.get_runtime_path(),"fanart.jpg") if item.folder : if len(item.extra)>0: addnewfolderextra( item.channel , item.action , item.category , item.title , item.url , item.thumbnail , item.plot , extradata = item.extra , totalItems = len(itemlist), fanart=item.fanart , context=item.context, show=item.show, fulltitle=item.fulltitle ) else: addnewfolder( item.channel , item.action , item.category , item.title , item.url , item.thumbnail , item.plot , totalItems = len(itemlist) , fanart = item.fanart, context = item.context, show=item.show, fulltitle=item.fulltitle ) else: if config.get_setting("player_mode")=="1": # SetResolvedUrl debe ser siempre "isPlayable = true" isPlayable = "true" if item.duration: addnewvideo( item.channel , item.action , item.category , item.server, item.title , item.url , item.thumbnail , item.plot , "" , duration = item.duration , fanart = item.fanart, IsPlayable=isPlayable,context = item.context , subtitle=item.subtitle, totalItems = len(itemlist), show=item.show, password = item.password, extra = item.extra, fulltitle=item.fulltitle ) else: addnewvideo( item.channel , item.action , item.category , item.server, item.title , item.url , item.thumbnail , item.plot, fanart = item.fanart, IsPlayable=isPlayable , context = item.context , subtitle = item.subtitle , totalItems = len(itemlist), show=item.show , password = item.password , extra=item.extra, fulltitle=item.fulltitle ) if viewmode == -1: viewmode = item.viewmode # Cierra el directorio xbmcplugin.setContent(pluginhandle,"Movies") xbmcplugin.setPluginCategory( handle=pluginhandle, category=category ) xbmcplugin.addSortMethod( handle=pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_NONE ) # Confluence - Thumbnails #xbmc.executebuiltin("Container.SetViewMode(500)") # Confluence - Info de medios 1 #xbmc.executebuiltin("Container.SetViewMode(504)") if viewmode==1: import xbmc xbmc.executebuiltin('Container.SetViewMode(%d)' % get_view_mode_id("thumbnail")) xbmcplugin.endOfDirectory( handle=pluginhandle, succeeded=True )
def listchannels(item): itemlist = [] try: idioma = config.get_setting("languagefilter") logger.info("channelselector.filterchannels idioma=%s" % idioma) langlistv = ["","ES","EN","IT","PT"] idiomav = langlistv[int(idioma)] logger.info("channelselector.filterchannels idiomav=%s" % idiomav) except: idiomav="" activechannels = [] channelslist =[] item.category=item.category.replace("L","latino").replace("M","music").replace("X","adult").replace("T","torrent").replace("VOS","vos").replace("F","movie").replace("S","serie").replace("D","documentary").replace("A","anime") for channel in os.listdir(os.path.join(config.get_runtime_path(),"channels")): if channel.endswith(".xml"): XMLData= open(os.path.join(config.get_runtime_path(),"channels",channel), "rb").read() ChannelData = {} ChannelData["category"] = re.compile("<category>([^<]*)</category>",re.DOTALL).findall(XMLData) ChannelData["title"] = re.compile("<name>([^<]*)</name>",re.DOTALL).findall(XMLData)[0] ChannelData["channel"] = re.compile("<id>([^<]*)</id>",re.DOTALL).findall(XMLData)[0] ChannelData["active"] = re.compile("<active>([^<]*)</active>",re.DOTALL).findall(XMLData)[0] ChannelData["adult"] = re.compile("<adult>([^<]*)</adult>",re.DOTALL).findall(XMLData)[0] ChannelData["language"] = re.compile("<language>([^<]*)</language>",re.DOTALL).findall(XMLData)[0] ChannelData["thumbnail"] = re.compile("<thumbnail>([^<]*)</thumbnail>",re.DOTALL).findall(XMLData)[0] if not ChannelData["thumbnail"]: ChannelData["thumbnail"] ="%s"+ChannelData["channel"]+".png" ChannelData["fanart"] = re.compile("<fanart>([^<]*)</fanart>",re.DOTALL).findall(XMLData)[0] if not ChannelData["active"] == "true": continue if ChannelData["adult"] == "true" and not config.get_setting("enableadultmode") == "true": continue if not item.category=="*" and not item.category in ChannelData["category"]: continue if not ChannelData["language"]=="" and not idiomav=="" and not idiomav.lower() in ChannelData["language"]: continue if ChannelData["channel"]=="tengourl": channelslist.append(Item(title=ChannelData["title"], channel=ChannelData["channel"], action="mainlist", thumbnail=ChannelData["thumbnail"] , fanart=ChannelData["fanart"], category=", ".join(ChannelData["category"])[:-2], language=ChannelData["language"] )) else: activechannels.append(Item(title=ChannelData["title"], channel=ChannelData["channel"], action="mainlist", thumbnail=ChannelData["thumbnail"] , fanart=ChannelData["fanart"] , category=", ".join(ChannelData["category"])[:-2], language=ChannelData["language"] )) if config.get_setting("personalchannel")=="true": channelslist.append( Item( title=config.get_setting("personalchannelname") ,action="mainlist", channel="personal" ,thumbnail=config.get_setting("personalchannellogo"), language="" , category="F,S,D,A" , type="generic" )) if config.get_setting("personalchannel2")=="true": channelslist.append( Item( title=config.get_setting("personalchannelname2") ,action="mainlist", channel="personal2" ,thumbnail=config.get_setting("personalchannellogo2"), language="" , category="F,S,D,A" , type="generic" )) if config.get_setting("personalchannel3")=="true": channelslist.append( Item( title=config.get_setting("personalchannelname3") ,action="mainlist", channel="personal3" ,thumbnail=config.get_setting("personalchannellogo3"), language="" , category="F,S,D,A" , type="generic" )) if config.get_setting("personalchannel4")=="true": channelslist.append( Item( title=config.get_setting("personalchannelname4") ,action="mainlist", channel="personal4" ,thumbnail=config.get_setting("personalchannellogo4"), language="" , category="F,S,D,A" , type="generic" )) if config.get_setting("personalchannel5")=="true": channelslist.append( Item( title=config.get_setting("personalchannelname5") ,action="mainlist", channel="personal5" ,thumbnail=config.get_setting("personalchannellogo5"), language="" , category="F,S,D,A" , type="generic" )) activechannels.sort(key=lambda item: item.title.lower().strip()) channelslist.extend(activechannels) return channelslist
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://"): 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 get_channel_local_path(channel_name): import xbmc local_channel_path = xbmc.translatePath( os.path.join( config.get_runtime_path() ,PLUGIN_NAME, channel_name+".py" ) ) local_compiled_path = xbmc.translatePath( os.path.join( config.get_runtime_path() ,PLUGIN_NAME, channel_name+".pyo" ) ) logger.info("local_channel_path="+local_channel_path) logger.info("local_compiled_path="+local_compiled_path) return local_channel_path , local_compiled_path
def Check(): import guitools progress = guitools.Dialog_ProgressBG("Pelisalacarta","Comprobando actualizaciones...") DownloadServers = [] DownloadChannels = [] ServersPath = os.path.join( config.get_runtime_path(), "servers" ) ServersIndexPath = os.path.join(config.get_data_path(), "Servers.json") ChannelsPath = os.path.join( config.get_runtime_path(), "channels" ) ChannelsIndexPath = os.path.join(config.get_data_path(), "Channels.json") if not os.path.isfile(ServersIndexPath): CreateIndex(ServersIndexPath,"servers") if not os.path.isfile(ChannelsIndexPath): CreateIndex(ChannelsIndexPath,"channels") #Servers progress.Actualizar(25, "Descargando lista de Servidores...") RemoteJSONData = json.loads(scrapertools.downloadpage(GitApi + "servers", headers=headers)) LocalJSONData = json.loads(open(ServersIndexPath,"r").read()) #open(ServersIndexPath.replace(".json","-remote.json"),"w").write(json.dumps(RemoteJSONData, indent=4, sort_keys=True)) if RemoteJSONData <> LocalJSONData: for Server in RemoteJSONData: if not Server in LocalJSONData: DownloadServers.append(Server) #Channels progress.Actualizar(50, "Descargando lista de Canales...") RemoteJSONData = json.loads(scrapertools.downloadpage(GitApi + "channels", headers=headers)) LocalJSONData = json.loads(open(ChannelsIndexPath,"r").read()) #open(ChannelsIndexPath.replace(".json","-remote.json"),"w").write(json.dumps(RemoteJSONData, indent=4, sort_keys=True)) progress.Actualizar(75, "Comprobando...") if RemoteJSONData <> LocalJSONData: for Channel in RemoteJSONData: if not Channel in LocalJSONData: logger.info(Channel) DownloadChannels.append(Channel) if DownloadServers or DownloadChannels: for File in DownloadServers: Progreso = DownloadServers.index(File) * 100 / (len(DownloadServers) + len(DownloadChannels)) progress.Actualizar(Progreso ,'Actualizando Archivo: "' + File["name"] + '"') open(os.path.join(config.get_runtime_path(), "servers", File["name"]),"wb").write(scrapertools.downloadpage(File["download_url"])) for File in DownloadChannels: Progreso = (DownloadChannels.index(File) + len(DownloadServers) ) * 100 / (len(DownloadServers) + len(DownloadChannels)) progress.Actualizar(Progreso ,'Actualizando Archivo: "' + File["name"] + '"') open(os.path.join(config.get_runtime_path(), "channels", File["name"]),"wb").write(scrapertools.downloadpage(File["download_url"])) CreateIndex(ServersIndexPath,"servers") CreateIndex(ChannelsIndexPath,"channels") progress.Actualizar(100, "Todos los canales y servidores estan actualizados") import time time.sleep(3) progress.Cerrar()
def actualiza(item): logger.info("pelisalacarta.channels.update_sports actualiza") error = False if item.select == "servertools": filename = os.path.join(config.get_runtime_path(), 'servers', 'servertools.py') url = "https://raw.githubusercontent.com/CmosGit/Mod_pelisalacarta_deportes/master/main-classic/servers/servertools.py" error = do_download(url, filename) if error: dialog_notification("Error", "Se ha producido un error en la actualización de los archivos") else: dialog_notification("Éxito", "Actualizado correctamente servertools.py") elif item.select == "channelselector": filename = os.path.join(config.get_runtime_path(), 'channelselector.py') url = "https://raw.githubusercontent.com/CmosGit/Mod_pelisalacarta_deportes/master/main-classic/channelselector.py" error = do_download(url, filename) if error: dialog_notification("Error", "Se ha producido un error en la actualización de los archivos") else: dialog_notification("Éxito", "Actualizado correctamente channelselector.py") else: url = "https://api.github.com/repos/CmosGit/Mod_pelisalacarta_deportes/git/trees/master?recursive=1" data = scrapertools.cachePage(url) data = jsontools.load_json(data) count = 0 progreso = dialog_progress("Progreso de la actualización", "Descargando...") for child in data["tree"]: if not child["path"].startswith("main-classic"): continue if child["type"] == "blob": url = "https://raw.githubusercontent.com/CmosGit/Mod_pelisalacarta_deportes/master/" + child["path"] # Progreso count += 1 percent = (count * 100) / len(data["tree"]) progreso.update(percent, "[B][COLOR red]Actualizado al %d%%[/COLOR][/B]" % int(percent), "Descargando archivo %s" % url.rsplit("/",1)[1]) git_file = child["path"].replace("main-classic/","") filename = os.path.join(config.get_runtime_path(), git_file) error_download = do_download(url, filename) if error_download: error = True url = "https://raw.githubusercontent.com/CmosGit/Mod_pelisalacarta_deportes/master/actualizador/update_sports.xml" error = do_download(url,LOCAL_XML_FILE) count += 1 progreso.close() if error: dialog_notification("Error", "Se ha producido un error en la actualización de los archivos") else: dialog_notification("Actualizado correctamente", str(count)+" archivos actualizados")
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 show_channel_settings(list_controls=None, dict_values=None, caption="", callback=None, item=None, custom_button=None, channelpath=None): """ Muestra un cuadro de configuracion personalizado para cada canal y guarda los datos al cerrarlo. Parametros: ver descripcion en xbmc_config_menu.SettingsWindow @param list_controls: lista de elementos a mostrar en la ventana. @type list_controls: list @param dict_values: valores que tienen la lista de elementos. @type dict_values: dict @param caption: titulo de la ventana @type caption: str @param callback: función que se llama tras cerrarse la ventana. @type callback: str @param item: item para el que se muestra la ventana de configuración. @type item: Item @param custom_button: botón personalizado, que se muestra junto a "OK" y "Cancelar". @type custom_button: dict @return: devuelve la ventana con los elementos @rtype: SettingsWindow """ from xbmc_config_menu import SettingsWindow return SettingsWindow("ChannelSettings.xml", config.get_runtime_path()) \ .start(list_controls=list_controls, dict_values=dict_values, title=caption, callback=callback, item=item, custom_button=custom_button, channelpath=channelpath)
def start(): logger.info("pelisalacarta server init...") config.verify_directories_created() try: import HTTPServer HTTPServer.start() import WebSocket WebSocket.start(ProcessRequest,MostrarInfo) # Da por levantado el servicio logger.info("--------------------------------------------------------------------") logger.info("Pelisalacarta Iniciado") logger.info("La URL para acceder es http://" + myip + ":" + str(PORT)) logger.info("WebSocket Server iniciado en ws://"+ myip + ":" + str(WebsocketPort)) 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("library_path")) logger.info("Cache Path : " + config.get_setting("cache.dir")) logger.info("Cookies Path : " + config.get_setting("cookies.dir")) logger.info("--------------------------------------------------------------------") MostrarInfo() Start = True while Start: pass except KeyboardInterrupt: print 'Deteniendo el servidor' HTTPServer.stop() WebSocket.stop() Start= False
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 update_channels(): channel_path = os.path.join(config.get_runtime_path(), "channels", '*.xml') channel_files = glob.glob(channel_path) # ---------------------------- import xbmcgui progress = xbmcgui.DialogProgressBG() progress.create("Update channels list") # ---------------------------- for index, channel in enumerate(channel_files): # ---------------------------- percentage = index * 100 / len(channel_files) # ---------------------------- channel_id = os.path.basename(channel)[:-4] t = Thread(target=updater.updatechannel, args=[channel_id]) t.setDaemon(True) t.start() # ---------------------------- progress.update(percentage, ' Update channel: ' + channel_id) # ---------------------------- # ---------------------------- progress.close()
def findvideos(item): logger.info("pelisalacarta.altorrent findvideos") itemlist = [] th = Thread(target=get_art(item)) th.setDaemon(True) th.start() data = httptools.downloadpage(item.url).data data = re.sub(r"\n|\r|\t|\s{2}| ","",data) enlaces = scrapertools.find_multiple_matches(data,'id="modal-quality-\w+"><span>(.*?)</span>.*?class="quality-size">(.*?)</p>.*?href="([^"]+)"') for calidad,size,url in enlaces: title ="[COLOR palegreen][B]Torrent[/B][/COLOR]"+" "+"[COLOR chartreuse]"+calidad+"[/COLOR]"+"[COLOR teal] ( [/COLOR]"+"[COLOR forestgreen]"+size+"[/COLOR]"+"[COLOR teal] )[/COLOR]" itemlist.append( Item(channel=item.channel, title = title, url=url, action="play",server="torrent", fanart=item.fanart,thumbnail= item.thumbnail,extra=item.extra,InfoLabels=item.infoLabels, folder=False) ) dd=scrapertools.find_single_match(data,'button-green-download-big".*?href="([^"]+)"><span class="icon-play">') if dd: if item.library: itemlist.append( Item(channel=item.channel, title = "[COLOR floralwhite][B]Online[/B][/COLOR]" , url=dd, action="dd_y_o", thumbnail="http://imgur.com/mRmBIV4.png", fanart=item.extra.split("|")[0],contentType=item.contentType, extra=item.extra, folder=True) ) else: videolist = servertools.find_video_items(data=str(dd)) for video in videolist: icon_server = os.path.join( config.get_runtime_path() , "resources" , "images" , "servers" , "server_"+video.server+".png" ) if not os.path.exists(icon_server): icon_server = "" itemlist.append(Item(channel=item.channel ,url=video.url, server=video.server,title="[COLOR floralwhite][B]"+video.server+"[/B][/COLOR]",thumbnail=icon_server,fanart=item.extra.split("|")[1], action="play", folder=False) ) if item.library and config.get_library_support() and itemlist : infoLabels = {'tmdb_id': item.infoLabels['tmdb_id'], 'title': item.infoLabels['title']} itemlist.append(Item(channel=item.channel, title="Añadir esta película a la biblioteca", action="add_pelicula_to_library", url=item.url, infoLabels=infoLabels, text_color="0xFFe5ffcc", thumbnail='http://imgur.com/DNCBjUB.png',extra="library")) return itemlist
def channel_config(item): from platformcode import platformtools import os return platformtools.show_channel_settings( channelpath=os.path.join(config.get_runtime_path(), "channels", item.config) )
def MostrarInfo(): os.system('cls' if os.name == 'nt' else 'clear') print ("--------------------------------------------------------------------") print ("Pelisalacarta Iniciado") print ("La URL para acceder es http://" + myip + ":" + str(PORT)) print ("WebSocket Server iniciado en ws://"+ myip + ":" + config.get_setting("websocket.port")+"/") print ("--------------------------------------------------------------------") print ("Runtime Path : " + config.get_runtime_path()) print ("Data Path : " + config.get_data_path()) print ("Download Path : " + config.get_setting("downloadpath") ) print ("DownloadList Path : " + config.get_setting("downloadlistpath")) print ("Bookmark Path : " + config.get_setting("bookmarkpath")) print ("Library Path : " + config.get_setting("library_path")) print ("Cache Path : " + config.get_setting("cache.dir")) print ("Cookies Path : " + config.get_setting("cookies.dir")) print ("--------------------------------------------------------------------") conexiones = [] for a in sys.argv: conexiones.append(sys.argv[a]["Socket"].client.getpeername()[0]) if len(conexiones) >0: print ("Clientes conectados:") for conexion in conexiones: print (conexion) else: print ("No hay conexiones")
def findvideos(item): logger.info("pelisalacarta.verseriesonlinetv findvideos") itemlist = [] data = httptools.downloadpage(item.url).data patron = '<td><a href="([^"]+)".*?<img src="([^"]+)" title="([^<]+)" .*?<td>([^<]+)</td>.*?<td>([^<]+)</td>' matches = re.compile(patron,re.DOTALL).findall(data) print matches for scrapedurl, scrapedthumbnail,scrapedserver,scrapedidioma,scrapedcalidad in matches: server = scrapertools.get_match(scrapedserver,'(.*?)[.]') icon_server = os.path.join( config.get_runtime_path() , "resources" , "images" , "servers" , "server_"+server+".png" ) icon_server= re.sub(r"tv|com|net|","",icon_server) icon_server = icon_server.replace('streamin','streaminto') icon_server = icon_server.replace('ul','uploadedto') if not os.path.exists(icon_server): icon_server = scrapedthumbnail scrapedserver= scrapedserver.replace(scrapedserver,"[COLOR darkorange][B]"+"["+scrapedserver+"]"+"[/B][/COLOR]") scrapedidioma=scrapedidioma.replace(scrapedidioma,"[COLOR lawngreen][B]"+"--"+scrapedidioma+"--"+"[/B][/COLOR]") scrapedcalidad=scrapedcalidad.replace(scrapedcalidad,"[COLOR floralwhite][B]"+scrapedcalidad+"[/B][/COLOR]") title = scrapedserver + scrapedidioma+scrapedcalidad itemlist.append( Item(channel=item.channel, title = title , action="play", url=scrapedurl, thumbnail=icon_server, fanart=item.show.split("|")[6], extra = item.thumbnail, folder=True) ) return itemlist
def play_from_library(item): """ Los .strm al reproducirlos desde kodi, este espera que sea un archivo "reproducible" asi que no puede contener más items, como mucho se puede colocar un dialogo de seleccion. Esto lo solucionamos "engañando a kodi" y haciendole creer que se ha reproducido algo, asi despues mediante "Container.Update()" cargamos el strm como si un item desde dentro de pelisalacarta se tratara, quitando todas las limitaciones y permitiendo reproducir mediante la funcion general sin tener que crear nuevos métodos para la biblioteca. @type item: item @param item: elemento con información """ logger.info("pelisalacarta.platformcode.launcher play_from_library") # logger.debug("item: \n" + item.tostring('\n')) import xbmcgui import xbmcplugin import xbmc # Intentamos reproducir una imagen (esto no hace nada y ademas no da error) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem(path=os.path.join(config.get_runtime_path(), "icon.png"))) # Por si acaso la imagen hiciera (en futuras versiones) le damos a stop para detener la reproduccion xbmc.Player().stop() # modificamos el action (actualmente la biblioteca necesita "findvideos" ya que es donde se buscan las fuentes item.action = "findvideos" # y volvemos a lanzar kodi xbmc.executebuiltin("Container.Update(" + sys.argv[0] + "?" + item.tourl() + ")") return
def update_servers(): server_path = os.path.join(config.get_runtime_path(), "servers", '*.xml') server_files = sorted(glob.glob(server_path)) # ---------------------------- import xbmc import xbmcgui progress = xbmcgui.DialogProgressBG() progress.create("Update servers list") # ---------------------------- for index, server in enumerate(server_files): # ---------------------------- percentage = index * 100 / len(server_files) # ---------------------------- server_name = os.path.basename(server)[:-4] t = Thread(target=updater.update_server, args=[server_name]) t.setDaemon(True) t.start() # ---------------------------- progress.update(percentage, ' Update server: ' + server_name) # ---------------------------- while threading.active_count() >= MAX_THREADS: xbmc.sleep(500) # ---------------------------- progress.close()
def get_server_parameters(server): server=scrapertools.find_single_match(server,'([^\.]+)') try: if os.path.isfile(os.path.join(config.get_runtime_path(),"servers", server + ".xml")): JSONFile = xml2dict(os.path.join(config.get_runtime_path(),"servers", server + ".xml"))["server"] elif os.path.isfile(os.path.join(config.get_runtime_path(),"servers", "debriders", server + ".xml")): JSONFile = xml2dict(os.path.join(config.get_runtime_path(),"servers", "debriders", server + ".xml"))["server"] if type(JSONFile["premium"]) == dict: JSONFile["premium"]=JSONFile["premium"]["value"] if JSONFile["premium"] == "": JSONFile["premium"]=[] if type(JSONFile["premium"]) == str and not JSONFile["premium"] == "": JSONFile["premium"]=[JSONFile["premium"]] return JSONFile except: logger.info("Error al cargar el servidor: " + server) import traceback logger.info(traceback.format_exc()) return {}
def filterchannels(category,preferred_thumb=""): logger.info("channelselector.filterchannels") try: idioma = config.get_setting("languagefilter") logger.info("channelselector.filterchannels idioma=%s" % idioma) langlistv = ["","ES","EN","IT","PT"] idiomav = langlistv[int(idioma)] logger.info("channelselector.filterchannels idiomav=%s" % idiomav) except: idiomav="" activechannels = [] channelslist =[] category=category.replace("L","latino").replace("M","music").replace("X","adult").replace("T","torrent").replace("VOS","vos").replace("F","movie").replace("S","serie").replace("D","documentary").replace("A","anime").replace("*","all") channel_path = os.path.join(config.get_runtime_path(),"channels") logger.info("channelselector.filterchannels channel_path="+channel_path) for channel in os.listdir(channel_path): logger.info("channelselector.filterchannels channel="+channel) if channel.endswith(".xml"): try: ChannelData = channeltools.get_channel_parameters(channel[:-4]) if not ChannelData["thumbnail"]: ChannelData["thumbnail"] = get_thumbnail_path(preferred_thumb)+ChannelData["channel"]+".png" else: # Si prefiere el bannermenu y el canal lo tiene, cambia ahora de idea if preferred_thumb=="bannermenu" and "bannermenu" in ChannelData: ChannelData["thumbnail"]=ChannelData["bannermenu"] if not ChannelData["active"] == "true": continue #Si no esta activo lo saltamos if ChannelData["adult"] == "true" and not config.get_setting("adult_mode") == "true": continue # Si es adulto y no estan activados lo saltamos if not category=="all" and not category in ChannelData["category"] and not "all" in ChannelData["category"]: continue #Si no corresponde la categoria lo saltamos if not ChannelData["language"]=="" and not idiomav=="" and not idiomav.lower() in ChannelData["language"]: continue #Si no corresponde el idioma lo saltamos if ChannelData["channel"]=="tengourl": channelslist.append(Item(title=ChannelData["title"], channel=ChannelData["channel"], action="mainlist", thumbnail=ChannelData["thumbnail"] , fanart=ChannelData["fanart"], category=", ".join(ChannelData["category"])[:-2], language=ChannelData["language"], type=ChannelData["type"] )) else: activechannels.append(Item(title=ChannelData["title"], channel=ChannelData["channel"], action="mainlist", thumbnail=ChannelData["thumbnail"] , fanart=ChannelData["fanart"] , category=", ".join(ChannelData["category"])[:-2], language=ChannelData["language"], type=ChannelData["type"] )) except: logger.info("Se ha producido un error al leer los datos del canal " + channel) import traceback logger.info(traceback.format_exc()) if config.get_setting("personalchannel")=="true": channelslist.append( Item( title=config.get_setting("personalchannelname") ,action="mainlist", channel="personal" ,thumbnail=config.get_setting("personalchannellogo"), language="" , category="F,S,D,A" , type="generic" )) if config.get_setting("personalchannel2")=="true": channelslist.append( Item( title=config.get_setting("personalchannelname2") ,action="mainlist", channel="personal2" ,thumbnail=config.get_setting("personalchannellogo2"), language="" , category="F,S,D,A" , type="generic" )) if config.get_setting("personalchannel3")=="true": channelslist.append( Item( title=config.get_setting("personalchannelname3") ,action="mainlist", channel="personal3" ,thumbnail=config.get_setting("personalchannellogo3"), language="" , category="F,S,D,A" , type="generic" )) if config.get_setting("personalchannel4")=="true": channelslist.append( Item( title=config.get_setting("personalchannelname4") ,action="mainlist", channel="personal4" ,thumbnail=config.get_setting("personalchannellogo4"), language="" , category="F,S,D,A" , type="generic" )) if config.get_setting("personalchannel5")=="true": channelslist.append( Item( title=config.get_setting("personalchannelname5") ,action="mainlist", channel="personal5" ,thumbnail=config.get_setting("personalchannellogo5"), language="" , category="F,S,D,A" , type="generic" )) activechannels.sort(key=lambda item: item.title.lower().strip()) channelslist.extend(activechannels) return channelslist
def add_items_to_kodi_directory(itemlist,parent_item): logger.info("tvalacarta.platformcode.xbmctools add_items_to_kodi_directory") pluginhandle = int( sys.argv[ 1 ] ) # Checks if channel provides context menu for items exec "import channels."+parent_item.channel+" as channelmodule" channel_provides_context_menu = hasattr(channelmodule, 'get_context_menu_for_item') for item in itemlist: # If video has no fanart, here is assigned a new one if item.fanart=="": channel_fanart = os.path.join( config.get_runtime_path(), 'resources', 'images', 'fanart', item.channel+'.jpg') if os.path.exists(channel_fanart): item.fanart = channel_fanart else: item.fanart = os.path.join(config.get_runtime_path(),"fanart.jpg") # Add item to kodi directory add_item_to_kodi_directory(item,itemlist,channel_provides_context_menu) # Closes the XBMC directory xbmcplugin.setPluginCategory( handle=pluginhandle, category=parent_item.category ) xbmcplugin.addSortMethod( handle=pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_NONE ) # Forces the view mode if config.get_setting("forceview")=="true": import plugintools if parent_item.view=="list": plugintools.set_view( plugintools.LIST ) elif parent_item.view=="programs": plugintools.set_view( plugintools.TV_SHOWS ) elif parent_item.view=="channels" or parent_item.view=="thumbnails": if config.get_platform()=="kodi-krypton": plugintools.set_view( plugintools.TV_SHOWS ) else: plugintools.set_view( plugintools.THUMBNAIL ) elif parent_item.view=="videos": plugintools.set_view( plugintools.EPISODES ) xbmcplugin.endOfDirectory( handle=pluginhandle, succeeded=True )
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.error("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.error( "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.error( "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.error( "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 try: shutil.copy(path_video_temp,full_path_video_new ) copy = True logger.info("nuevo path ="+full_path_video_new) xbmc.sleep(2 * 1000) 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.error("Error : no se pudo copiar") xbmc.sleep(1 * 1000) if copy: if xbmc.Player().isPlayingVideo(): xbmc.executebuiltin("RunScript(script.xbmc.subtitles)") while xbmc.Player().isPlayingVideo(): continue xbmc.sleep(1 * 1000) os.remove(full_path_video_new) try: if full_path_tvshow!="": os.rmdir(full_path_tvshow) except OSError:pass
import sys import os import bridge import channelselector from core import config from core.item import Item from core import channeltools from core import servertools from DumbTools import DumbKeyboard #Añadimos "lib" al path sys.path.append(os.path.join(config.get_runtime_path(), 'lib')) # Passing log and config to an external library # Credits to https://gist.github.com/mikew/5011984 bridge.init(Log, Prefs, Locale) ################################################################################################### PLUGIN_TITLE = "pelisalacarta" ART_DEFAULT = "art-default.jpg" ICON_DEFAULT = "icon-default.png" ################################################################################################### def Start(): Plugin.AddPrefixHandler("/video/pelisalacarta", mainlist, PLUGIN_TITLE, ICON_DEFAULT, ART_DEFAULT) ''' ViewModes = {"List": 65586, "InfoList": 65592, "MediaPreview": 458803, "Showcase": 458810, "Coverflow": 65591, "PanelStream": 131124, "WallStream": 131125, "Songs": 65593, "Seasons": 65593, "Albums": 131123,
import urllib2, re import os from core import scrapertools from core import logger from core import config from core import jsontools from core.item import Item from core import servertools import xbmc from core.scrapertools import decodeHtmlentities as dhe import datetime from core import httptools __channel__ = "topbongda" song = os.path.join(config.get_runtime_path(), "music", 'Easy.mp3') def agendaglobal(item): itemlist = [] try: itemlist = mainlist(item) except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def channel_config(item): return platformtools.show_channel_settings(channelpath=os.path.join(config.get_runtime_path(), "channels", item.channel))
def server_config(item): return platformtools.show_channel_settings(channelpath=filetools.join(config.get_runtime_path(), "servers", item.config))
from core import config import xbmcplugin import xbmcaddon import xbmc import xbmcgui from core.item import Item from core import servertools from core.scrapertools import decodeHtmlentities as dhe import random import time import datetime import locale __channel__ = "lfootballws" song = os.path.join(config.get_runtime_path(), 'music', 'queen-we-will-rock-you.mp3') host = "http://lfootball.ws/" DEBUG = config.get_setting("debug") def agendaglobal(item): itemlist = [] try: itemlist = mainlist(item) except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return []
def getchanneltypes(preferred_thumb=""): logger.info("channelselector getchanneltypes") # Lista de categorias valid_types = ["movie", "serie", "anime", "documentary", "vos", "torrent", "latino", "adult"] dict_cat_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)} # Lee la lista de canales channel_path = os.path.join(config.get_runtime_path(), "channels", '*.xml') logger.info("channelselector.getchanneltypes channel_path="+channel_path) channel_files = glob.glob(channel_path) channel_language = config.get_setting("channel_language") logger.info("channelselector.getchanneltypes channel_language="+channel_language) # Construye la lista de tipos channel_types = [] for index, channel in enumerate(channel_files): logger.info("channelselector.getchanneltypes channel="+channel) if channel.endswith(".xml"): try: channel_parameters = channeltools.get_channel_parameters(channel[:-4]) logger.info("channelselector.filterchannels channel_parameters="+repr(channel_parameters)) # Si es un canal para adultos y el modo adulto está desactivado, se lo salta if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "false": continue # Si el canal está en un idioma filtrado if channel_language != "all" and channel_parameters["language"] != channel_language: continue categories = channel_parameters["categories"] for category in categories: logger.info("channelselector.filterchannels category="+category) if category not in channel_types and category in valid_types: channel_types.append(category) except: logger.info("Se ha producido un error al leer los datos del canal " + channel + traceback.format_exc()) logger.info("channelselector.getchanneltypes Encontrados:") for channel_type in channel_types: logger.info("channelselector.getchanneltypes channel_type="+channel_type) # 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="movie")) logger.info("channelselector.getchanneltypes Ordenados:") for channel_type in valid_types: logger.info("channelselector.getchanneltypes channel_type="+channel_type) if channel_type in channel_types: title = dict_cat_lang.get(channel_type, channel_type) itemlist.append(Item(title=title, channel="channelselector", action="filterchannels", category=title, channel_type= channel_type, viewmode="movie", thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb), "thumb_canales_"+channel_type+".png"))) return itemlist
def main(): if scrapertools.wait_for_internet(retry=10): # -- Update channels from repository streamondemand ------ try: from core import update_channels except: logger.info( "streamondemand.library_service Error in update_channels") # ---------------------------------------------------------------------- # -- Update servertools and servers from repository streamondemand ------ try: from core import update_servers except: logger.info( "streamondemand.library_service Error in update_servers") # ---------------------------------------------------------------------- logger.info("streamondemand.library_service Actualizando series...") p_dialog = None try: if config.get_setting("updatelibrary") == "true": heading = 'Aggiornamento biblioteca....' p_dialog = platformtools.dialog_progress_bg( 'streamondemand', heading) p_dialog.update(0, '') show_list = [] for path, folders, files in filetools.walk( library.TVSHOWS_PATH): show_list.extend([ filetools.join(path, f) for f in files if f == "tvshow.json" ]) # fix float porque la division se hace mal en python 2.x t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): serie = Item().fromjson(filetools.read(tvshow_file)) path = filetools.dirname(tvshow_file) logger.info("streamondemand.library_service serie=" + serie.contentSerieName) logger.info( "streamondemand.library_service Actualizando " + path) logger.info("streamondemand.library_service url " + serie.url) show_name = serie.contentTitle if show_name == "": show_name = serie.show p_dialog.update(int(math.ceil((i + 1) * t)), heading, show_name) # si la serie esta activa se actualiza if serie.active: try: pathchannels = filetools.join( config.get_runtime_path(), "channels", serie.channel + '.py') logger.info( "streamondemand.library_service Cargando canal: " + pathchannels + " " + serie.channel) obj = imp.load_source(serie.channel, pathchannels) itemlist = obj.episodios(serie) try: library.save_library_episodes( path, itemlist, serie, True) except Exception as ex: logger.info( "streamondemand.library_service Error al guardar los capitulos de la serie" ) template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format( type(ex).__name__, ex.args) logger.info(message) except Exception as ex: logger.error( "Error al obtener los episodios de: {0}". format(serie.show)) template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format( type(ex).__name__, ex.args) logger.info(message) p_dialog.close() else: logger.info( "No actualiza la biblioteca, está desactivado en la configuración de streamondemand" ) except Exception as ex: logger.info( "streamondemand.library_service Se ha producido un error al actualizar las series" ) template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) logger.info(message) if p_dialog: p_dialog.close()
def run(self, path): if path == "/": f = open( os.path.join(config.get_runtime_path(), "platformcode", "template", "page.html"), "rb") self.handler.send_response(200) self.handler.send_header('Content-type', 'text/html') self.handler.end_headers() respuesta = f.read() respuesta = respuesta.replace( "{$WSPORT}", str(config.get_setting("websocket.port"))) self.handler.wfile.write(respuesta) f.close() elif path.startswith("/local/"): import base64 import urllib Path = path.replace("/local/", "").split("/")[0] Path = base64.b64decode(urllib.unquote_plus(Path)) Size = int(os.path.getsize(Path.decode("utf8"))) f = open(Path.decode("utf8"), "rb") if not self.handler.headers.get("range") == None: if "=" in str( self.handler.headers.get("range")) and "-" in str( self.handler.headers.get("range")): Inicio = int( self.handler.headers.get("range").split("=")[1].split( "-")[0]) if self.handler.headers.get("range").split("=")[1].split( "-")[1] <> "": Fin = int( self.handler.headers.get("range").split("=") [1].split("-")[1]) else: Fin = Size - 1 else: Inicio = 0 Fin = Size - 1 if not Fin > Inicio: Fin = Size - 1 if self.handler.headers.get("range") == None: logger.info( "-------------------------------------------------------") logger.info("Solicitando archivo local: " + Path) logger.info( "-------------------------------------------------------") self.handler.send_response(200) self.handler.send_header("Content-Disposition", "attachment; filename=video.mp4") self.handler.send_header('Accept-Ranges', 'bytes') self.handler.send_header('Content-Length', str(Size)) self.handler.send_header("Connection", "close") self.handler.end_headers() while True: time.sleep(0.2) buffer = f.read(1024 * 250) if not buffer: break self.handler.wfile.write(buffer) self.handler.wfile.close() f.close() else: logger.info( "-------------------------------------------------------") logger.info("Solicitando archivo local: " + Path) logger.info("Rango: " + str(Inicio) + "-" + str(Fin) + "/" + str(Size)) logger.info( "-------------------------------------------------------") f.seek(Inicio) self.handler.send_response(206) self.handler.send_header("Content-Disposition", "attachment; filename=video.mp4") self.handler.send_header('Accept-Ranges', 'bytes') self.handler.send_header('Content-Length', str(Fin - Inicio)) self.handler.send_header( 'Content-Range', str(Inicio) + "-" + str(Fin) + "/" + str(Size)) self.handler.send_header("Connection", "close") self.handler.end_headers() while True: time.sleep(0.2) buffer = f.read(1024 * 250) if not buffer: break self.handler.wfile.write(buffer) self.handler.wfile.close() f.close() elif path.startswith("/media/"): file = os.path.join(config.get_runtime_path(), "platformcode", "template", path[7:]) from mimetypes import MimeTypes mime = MimeTypes() mime_type = mime.guess_type(file) try: mim = mime_type[0] except: mim = "" f = open(file, "rb") self.handler.send_response(200) self.handler.send_header('Content-type', mim) self.handler.end_headers() self.handler.wfile.write(f.read()) f.close()
# # You should have received a copy of the GNU General Public License # along with pelisalacarta 4. If not, see <http://www.gnu.org/licenses/>. # -------------------------------------------------------------------------------- # update_servers.py # -------------------------------------------------------------------------------- import os import urlparse from core import config from core import scrapertools from core import servertools remote_url = "https://raw.githubusercontent.com/tvalacarta/pelisalacarta/master/python/main-classic/servers/" local_folder = os.path.join( config.get_runtime_path(), "servers" ) ### Procedures def update_servers(): update_servers_files( read_remote_servers_list( dict( read_local_servers_list() ) ) ) def update_servers_files( update_servers_list ): # ---------------------------- from platformcode import platformtools progress = platformtools.dialog_progress_bg( "Update servers list" )
def buscartrailer(item, trailers=[]): logger.info() # Lista de acciones si se ejecuta desde el menú contextual if item.action == "manual_search" and item.contextual: itemlist = manual_search(item) item.contentTitle = itemlist[0].contentTitle elif 'search' in item.action and item.contextual: itemlist = globals()[item.action](item) else: # Se elimina la opción de Buscar Trailer del menú contextual para evitar redundancias if type(item.context) is str and "buscar_trailer" in item.context: item.context = item.context.replace("buscar_trailer", "") elif type(item.context) is list and "buscar_trailer" in item.context: item.context.remove("buscar_trailer") item.text_color = "" itemlist = [] if item.contentTitle != "": item.contentTitle = item.contentTitle.strip() elif keyboard: fulltitle = re.sub('\[\/*(B|I|COLOR)\s*[^\]]*\]', '', item.fulltitle.strip()) item.contentTitle = platformtools.dialog_input(default=fulltitle, heading="Introduce el título a buscar") if item.contentTitle is None: item.contentTitle = fulltitle else: item.contentTitle = item.contentTitle.strip() else: fulltitle = re.sub('\[\/*(B|I|COLOR)\s*[^\]]*\]', '', item.fulltitle.strip()) item.contentTitle = fulltitle item.year = item.infoLabels['year'] logger.info("Búsqueda: %s" % item.contentTitle) logger.info("Año: %s" % item.year) if item.infoLabels['trailer'] and not trailers: url = item.infoLabels['trailer'] if "youtube" in url: url = url.replace("embed/", "watch?v=") titulo, url, server = servertools.findvideos(url)[0] title = "Trailer por defecto [" + server + "]" itemlist.append(item.clone(title=title, url=url, server=server, action="play")) if item.show or item.infoLabels['tvshowtitle'] or item.contentType != "movie": tipo = "tv" else: tipo = "movie" try: if not trailers: itemlist.extend(tmdb_trailers(item, tipo)) else: for trailer in trailers: title = trailer['name'] + " [" + trailer['size'] + "p] (" + trailer['language'].replace("en", "ING")\ .replace("es", "ESP")+") [tmdb/youtube]" itemlist.append(item.clone(action="play", title=title, url=trailer['url'], server="youtube")) except: import traceback logger.error(traceback.format_exc()) if item.contextual: title = "[COLOR green]%s[/COLOR]" else: title = "%s" itemlist.append(item.clone(title=title % "Búsqueda en Youtube", action="youtube_search", text_color="green")) itemlist.append(item.clone(title=title % "Búsqueda en Filmaffinity", action="filmaffinity_search", text_color="green")) # Si se trata de una serie, no se incluye la opción de buscar en Abandomoviez if not item.show and not item.infoLabels['tvshowtitle']: itemlist.append(item.clone(title=title % "Búsqueda en Abandomoviez", action="abandomoviez_search", text_color="green")) itemlist.append(item.clone(title=title % "Búsqueda en Jayhap (Youtube, Vimeo & Dailymotion)", action="jayhap_search", text_color="green")) if item.contextual: global window_select, result select = Select("DialogSelect.xml", config.get_runtime_path(), item=item, itemlist=itemlist, caption="Buscando: "+item.contentTitle) window_select.append(select) select.doModal() if item.windowed: return result, window_select else: return itemlist
def controller(plugin_name, port, host, path, headers): # Lee la plantilla file_plantilla = open( os.path.join(config.get_runtime_path(), "platformcode", "mediaserver", "template", "page.html")) plantilla_pagina = file_plantilla.read() file_plantilla.close() file_plantilla = open( os.path.join(config.get_runtime_path(), "platformcode", "mediaserver", "template", "item.html")) plantilla_item = file_plantilla.read() file_plantilla.close() itemlist_respuesta = [] respuesta = "" try: # Menú principal if path == "/" + platform_name.PLATFORM_NAME + "/" or path == "/" + platform_name.PLATFORM_NAME: respuesta = plantilla_pagina.replace("{$page-title}", "pelisalacarta") 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") from core import updater actualizado = updater.updatechannel("channelselector") if actualizado: itemlist_respuesta.append( Item( url="http://" + host + "/" + platform_name.PLATFORM_NAME, title="¡Lista de canales actualizada¡", thumbnail= "http://pelisalacarta.mimediacenter.info/squares/Crystal_Clear_action_info.png", plot=channel.plot)) 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": itemlist_respuesta.append( Item(title=channel.title, url="http://" + host + "/" + platform_name.PLATFORM_NAME + "/" + base64.b64encode(channel.serialize()).replace( "/", "%2F"), thumbnail=channel.thumbnail, plot=channel.plot)) else: item = extract_item_from_url(path) respuesta = plantilla_pagina.replace("{$page-title}", item.title) if item.channel == "channelselector" and item.action == "channeltypes": import channelselector channelslist = channelselector.getchanneltypes() for channel in channelslist: itemlist_respuesta.append( Item(url="http://" + host + "/" + platform_name.PLATFORM_NAME + "/" + base64.b64encode(channel.serialize()).replace( "/", "%2F"), title=channel.title, thumbnail=channel.thumbnail, plot=channel.plot)) 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" itemlist_respuesta.append( Item(url="http://" + host + "/" + platform_name.PLATFORM_NAME + "/" + base64.b64encode(channel.serialize()).replace( "/", "%2F"), title=channel.title, thumbnail=channel.thumbnail, plot=channel.plot)) else: itemlist, channel = getitems(item) # 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": if item.server == "": item.server = "none" if item.url == "": item.url = "none" url = "http://%s/%s" % ( host + "/" + platform_name.PLATFORM_NAME, base64.b64encode(item.serialize()).replace( "/", "%2F")) if item.thumbnail == "": item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/search.png" itemlist_respuesta.append( Item(url=url, title=item.title, thumbnail=item.thumbnail, plot=item.plot)) 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-" if item.thumbnail == "": #if item.server!="" and item.server.lower()!="directo": # item.thumbnail = "http://pelisalacarta.mimediacenter.info/servers/"+item.server+".png" #else: if item.folder: item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/folder.png" else: item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/file.png" url = "http://%s/%s" % ( host + "/" + platform_name.PLATFORM_NAME, base64.b64encode(item.serialize()).replace( "/", "%2F")) itemlist_respuesta.append( Item(url=url, title=item.title, thumbnail=item.thumbnail, plot=item.plot)) logger.info(" Nivel intermedio " + url) else: if item.thumbnail == "": #if item.server!="" and item.server.lower()!="directo": # item.thumbnail = "http://pelisalacarta.mimediacenter.info/servers/"+item.server+".png" #else: if item.folder: item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/folder.png" else: item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/file.png" itemlist_respuesta.append( Item(url=item.url, title=item.title, thumbnail=item.thumbnail, plot=item.plot)) logger.info(" Video " + item.url) itemlist_string = "" for item in itemlist_respuesta: item_string = plantilla_item item_string = item_string.replace("{$title}", item.title) item_string = item_string.replace("{$url}", item.url) item_string = item_string.replace("{$thumbnail}", item.thumbnail) item_string = item_string.replace( "{$plot}", scrapertools.htmlclean(item.plot)) itemlist_string = itemlist_string + item_string + "\n" respuesta = respuesta.replace("{$itemlist}", itemlist_string) except: import sys for line in sys.exc_info(): logger.error("%s" % line) return respuesta
def filterchannels(category, preferred_thumb=""): logger.info() channelslist = [] # Si category = "allchannelstatus" es que estamos activando/desactivando canales appenddisabledchannels = False if category == "allchannelstatus": category = "all" appenddisabledchannels = True # Lee la lista de canales channel_path = os.path.join(config.get_runtime_path(), "channels", '*.xml') logger.info("channel_path=" + channel_path) channel_files = glob.glob(channel_path) logger.info("channel_files encontrados " + str(len(channel_files))) channel_language = config.get_setting("channel_language") logger.info("channel_language=" + channel_language) if channel_language == "": channel_language = "all" logger.info("channel_language=" + channel_language) for channel in channel_files: logger.info("channel=" + channel) try: channel_parameters = channeltools.get_channel_parameters( channel[:-4]) # si el canal no es compatible, no se muestra if not channel_parameters["compatible"]: continue # Si no es un canal lo saltamos if not channel_parameters["channel"]: continue logger.info("channel_parameters=" + repr(channel_parameters)) # Si prefiere el bannermenu y el canal lo tiene, cambia ahora de idea if preferred_thumb == "bannermenu" and "bannermenu" in channel_parameters: channel_parameters["thumbnail"] = channel_parameters[ "bannermenu"] # Se salta el canal si no está activo y no estamos activando/desactivando los canales channel_status = config.get_setting("enabled", channel_parameters["channel"]) if channel_status is None: # si channel_status no existe es que NO HAY valor en _data.json channel_status = channel_parameters["active"] # fix temporal para solucionar que enabled aparezca como "true/false"(str) y sea true/false(bool) # TODO borrar este fix en la versión > 4.2.1, ya que no sería necesario else: if isinstance(channel_status, basestring): if channel_status == "true": channel_status = True else: channel_status = False config.set_setting("enabled", channel_status, channel_parameters["channel"]) if channel_status != True: # si obtenemos el listado de canales desde "activar/desactivar canales", y el canal está desactivado # lo mostramos, si estamos listando todos los canales desde el listado general y está desactivado, # no se muestra if appenddisabledchannels != True: continue # Se salta el canal para adultos si el modo adultos está desactivado if channel_parameters["adult"] == True and config.get_setting( "adult_mode") == 0: continue # Se salta el canal si está en un idioma filtrado if channel_language != "all" \ and channel_parameters["language"] != config.get_setting("channel_language"): continue # Se salta el canal si está en una categoria filtrado if category != "all" and category not in channel_parameters[ "categories"]: continue # Si tiene configuración añadimos un item en el contexto context = [] if channel_parameters["has_settings"]: context.append({ "title": "Configurar canal", "channel": "configuracion", "action": "channel_config", "config": channel_parameters["channel"] }) # Si ha llegado hasta aquí, lo añade channelslist.append( Item(title=channel_parameters["title"], channel=channel_parameters["channel"], action="mainlist", thumbnail=channel_parameters["thumbnail"], fanart=channel_parameters["fanart"], category=channel_parameters["title"], language=channel_parameters["language"], viewmode="list", version=channel_parameters["version"], context=context)) except: logger.error( "Se ha producido un error al leer los datos del canal " + channel) import traceback logger.error(traceback.format_exc()) channelslist.sort(key=lambda item: item.title.lower().strip()) if category == "all": if config.get_setting("personalchannel5") == True: channelslist.insert( 0, Item(title=config.get_setting("personalchannelname5"), action="mainlist", channel="personal5", thumbnail=config.get_setting("personalchannellogo5"), type="generic", viewmode="list")) if config.get_setting("personalchannel4") == True: channelslist.insert( 0, Item(title=config.get_setting("personalchannelname4"), action="mainlist", channel="personal4", thumbnail=config.get_setting("personalchannellogo4"), type="generic", viewmode="list")) if config.get_setting("personalchannel3") == True: channelslist.insert( 0, Item(title=config.get_setting("personalchannelname3"), action="mainlist", channel="personal3", thumbnail=config.get_setting("personalchannellogo3"), type="generic", viewmode="list")) if config.get_setting("personalchannel2") == True: channelslist.insert( 0, Item(title=config.get_setting("personalchannelname2"), action="mainlist", channel="personal2", thumbnail=config.get_setting("personalchannellogo2"), type="generic", viewmode="list")) if config.get_setting("personalchannel") == True: channelslist.insert( 0, Item(title=config.get_setting("personalchannelname"), action="mainlist", channel="personal", thumbnail=config.get_setting("personalchannellogo"), type="generic", viewmode="list")) channel_parameters = channeltools.get_channel_parameters("tengourl") # Si prefiere el bannermenu y el canal lo tiene, cambia ahora de idea if preferred_thumb == "bannermenu" and "bannermenu" in channel_parameters: channel_parameters["thumbnail"] = channel_parameters["bannermenu"] channelslist.insert( 0, Item(title="Tengo una URL", action="mainlist", channel="tengourl", thumbnail=channel_parameters["thumbnail"], type="generic", viewmode="list")) channel_parameters = channeltools.get_channel_parameters( "searchchannel") channelslist.insert( 0, Item(title="[COLOR gray]Cerca canale[/COLOR]", action="search", channel="searchchannel", thumbnail=channel_parameters["thumbnail"], type="generic", viewmode="movie")) return channelslist
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://"): 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 filterchannels(category,preferred_thumb=""): logger.info("channelselector.filterchannels") channelslist =[] # Lee la lista de canales channel_path = os.path.join( config.get_runtime_path() , "channels" , '*.xml' ) logger.info("channelselector.filterchannels channel_path="+channel_path) channel_files = glob.glob(channel_path) logger.info("channelselector.filterchannels channel_files encontrados "+str(len(channel_files))) channel_language = config.get_setting("channel_language") logger.info("channelselector.filterchannels channel_language="+channel_language) if channel_language=="": channel_language = "all" logger.info("channelselector.filterchannels channel_language="+channel_language) for index, channel in enumerate(channel_files): logger.info("channelselector.filterchannels channel="+channel) if channel.endswith(".xml"): try: channel_parameters = channeltools.get_channel_parameters(channel[:-4]) logger.info("channelselector.filterchannels channel_parameters="+repr(channel_parameters)) # Si prefiere el bannermenu y el canal lo tiene, cambia ahora de idea if preferred_thumb=="bannermenu" and "bannermenu" in channel_parameters: channel_parameters["thumbnail"] = channel_parameters["bannermenu"] # Se salta el canal si no está activo if not channel_parameters["active"] == "true": continue # Se salta el canal para adultos si el modo adultos está desactivado if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") != "true": continue # Se salta el canal si está en un idioma filtrado if channel_language!="all" and channel_parameters["language"]!=config.get_setting("channel_language"): continue # Se salta el canal si está en una categoria filtrado if category!="all" and category not in channel_parameters["categories"]: continue # Si ha llegado hasta aquí, lo añade channelslist.append(Item(title=channel_parameters["title"], channel=channel_parameters["channel"], action="mainlist", thumbnail=channel_parameters["thumbnail"] , fanart=channel_parameters["fanart"], category=channel_parameters["title"], language=channel_parameters["language"], viewmode="list" )) except: logger.info("Se ha producido un error al leer los datos del canal " + channel) import traceback logger.info(traceback.format_exc()) channelslist.sort(key=lambda item: item.title.lower().strip()) if category=="all": if config.get_setting("personalchannel5")=="true": channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname5") ,action="mainlist", channel="personal5" ,thumbnail=config.get_setting("personalchannellogo5") , type="generic" ,viewmode="list" )) if config.get_setting("personalchannel4")=="true": channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname4") ,action="mainlist", channel="personal4" ,thumbnail=config.get_setting("personalchannellogo4") , type="generic" ,viewmode="list" )) if config.get_setting("personalchannel3")=="true": channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname3") ,action="mainlist", channel="personal3" ,thumbnail=config.get_setting("personalchannellogo3") , type="generic" ,viewmode="list" )) if config.get_setting("personalchannel2")=="true": channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname2") ,action="mainlist", channel="personal2" ,thumbnail=config.get_setting("personalchannellogo2") , type="generic" ,viewmode="list" )) if config.get_setting("personalchannel")=="true": channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname") ,action="mainlist", channel="personal" ,thumbnail=config.get_setting("personalchannellogo") , type="generic" ,viewmode="list" )) channel_parameters = channeltools.get_channel_parameters("tengourl") # Si prefiere el bannermenu y el canal lo tiene, cambia ahora de idea if preferred_thumb=="bannermenu" and "bannermenu" in channel_parameters: channel_parameters["thumbnail"] = channel_parameters["bannermenu"] channelslist.insert( 0 , Item( title="Tengo una URL" ,action="mainlist", channel="tengourl" , thumbnail=channel_parameters["thumbnail"], type="generic" ,viewmode="list" )) return channelslist
def show_channel_settings(self, list_controls=None, dict_values=None, caption="", callback=None, item=None, custom_button=None, channelpath=None): from core import config from core import channeltools import inspect if not os.path.isdir( os.path.join(config.get_data_path(), "settings_channels")): os.mkdir(os.path.join(config.get_data_path(), "settings_channels")) title = caption if type(custom_button) == dict: custom_button = { "label": custom_button.get("label", ""), "function": custom_button.get("function", ""), "visible": bool(custom_button.get("visible", True)), "close": bool(custom_button.get("close", False)) } else: custom_button = None #Obtenemos el canal desde donde se ha echo la llamada y cargamos los settings disponibles para ese canal if not channelpath: channelpath = inspect.currentframe( ).f_back.f_back.f_code.co_filename channelname = os.path.basename(channelpath).replace(".py", "") #Si no tenemos list_controls, hay que sacarlos del xml del canal if not list_controls: #Si la ruta del canal esta en la carpeta "channels", obtenemos los controles y valores mediante chaneltools if os.path.join(config.get_runtime_path(), "channels") in channelpath: # La llamada se hace desde un canal list_controls, default_values = channeltools.get_channel_controls_settings( channelname) #En caso contrario salimos else: return None #Si no se pasan dict_values, creamos un dict en blanco if dict_values == None: dict_values = {} #Ponemos el titulo if caption == "": caption = str(config.get_localized_string( 30100)) + " -- " + channelname.capitalize() elif caption.startswith('@') and unicode(caption[1:]).isnumeric(): caption = config.get_localized_string(int(caption[1:])) JsonData = {} JsonData["action"] = "OpenConfig" JsonData["data"] = {} JsonData["data"]["title"] = caption JsonData["data"]["custom_button"] = custom_button JsonData["data"]["items"] = [] # Añadir controles for c in list_controls: if not "default" in c: c["default"] = "" if not "color" in c: c["color"] = "auto" if not "label" in c: continue #Obtenemos el valor if not c["id"] in dict_values: if not callback: c["value"] = config.get_setting(c["id"], channelname) else: c["value"] = c["default"] # Translation if c['label'].startswith('@') and unicode( c['label'][1:]).isnumeric(): c['label'] = str(config.get_localized_string(c['label'][1:])) if c["label"].endswith(":"): c["label"] = c["label"][:-1] if c['type'] == 'list': lvalues = [] for li in c['lvalues']: if li.startswith('@') and unicode(li[1:]).isnumeric(): lvalues.append(str(config.get_localized_string( li[1:]))) else: lvalues.append(li) c['lvalues'] = lvalues JsonData["data"]["items"].append(c) ID = self.send_message(JsonData) close = False while True: data = self.get_data(ID) if type(data) == dict: JsonData["action"] = "HideLoading" JsonData["data"] = {} self.send_message(JsonData) for v in data: if data[v] == "true": data[v] = True if data[v] == "false": data[v] = False if unicode(data[v]).isnumeric(): data[v] = int(data[v]) if not callback: for v in data: config.set_setting(v, data[v], channelname) return None else: exec "from channels import " + channelname + " as cb_channel" exec "return_value = cb_channel." + callback + "(item, data)" return return_value elif data == "custom_button": try: cb_channel = __import__('channels.%s' % channelname, None, None, ["channels.%s" % channelname]) except ImportError: logger.error('Imposible importar %s' % channelname) else: return_value = getattr(cb_channel, custom_button['function'])(item) if custom_button["close"] == True: return return_value elif data == False: return None
def run(item): itemlist = [] #Muestra el item en el log: PrintItems(item) #Control Parental, comprueba si es adulto o no if item.action == "mainlist": # Parental control if channeltools.is_adult( item.channel) and config.get_setting("adult_pin") != "": tecleado = platformtools.dialog_input( "", "Contraseña para canales de adultos", True) if tecleado is None or tecleado != config.get_setting("adult_pin"): platformtools.render_items(None, item) return #Importa el canal para el item, todo item debe tener un canal, sino sale de la función if item.channel: channelmodule = ImportarCanal(item) # If item has no action, stops here if item.action == "": logger.info("Item sin accion") itemlist = None #Action Play, para mostrar el menú con las opciones de reproduccion. elif item.action == "play": logger.info("play") # Si el canal tiene una acción "play" tiene prioridad if hasattr(channelmodule, 'play'): logger.info("executing channel 'play' method") itemlist = channelmodule.play(item) b_favourite = item.isFavourite if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True play_menu(item) elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist play_menu(item) else: platformtools.dialog_ok("plugin", "No hay nada para reproducir") else: logger.info("no channel 'play' method, executing core method") play_menu(item) itemlist = None #Action Search, para mostrar el teclado y lanzar la busqueda con el texto indicado. elif item.action == "search": logger.info("search") tecleado = platformtools.dialog_input() if not tecleado is None: itemlist = channelmodule.search(item, tecleado) else: itemlist = [] elif item.channel == "channelselector": import channelselector if item.action == "mainlist": itemlist = channelselector.getmainlist("bannermenu") if config.get_setting("check_for_plugin_updates") == True: logger.info( "channelselector.mainlist Verificar actualizaciones activado" ) 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\ndesde el listado principal" ) itemlist.insert( 0, Item( title="Actualizadr pelisalacarta a la versión " + version, version=version, channel="updater", action="update", thumbnail=os.path.join( config.get_runtime_path(), "resources", "images", "bannermenu", "thumb_update.png"))) except: platformtools.dialog_ok("No se puede conectar", "No ha sido posible comprobar", "si hay actualizaciones") logger.info("Fallo al verificar la actualización") else: logger.info("Verificar actualizaciones desactivado") if item.action == "getchanneltypes": itemlist = channelselector.getchanneltypes("bannermenu") if item.action == "filterchannels": itemlist = channelselector.filterchannels(item.channel_type, "bannermenu") #Todas las demas las intenta ejecturaren el siguiente orden: # 1. En el canal # 2. En el launcher # 3. Si no existe en el canal ni en el launcher guarda un error en el log else: #Si existe la funcion en el canal la ejecuta if hasattr(channelmodule, item.action): logger.info("Ejectuando accion: " + item.channel + "." + item.action + "(item)") exec "itemlist = channelmodule." + item.action + "(item)" #Si existe la funcion en el launcher la ejecuta elif hasattr(sys.modules[__name__], item.action): logger.info("Ejectuando accion: " + item.action + "(item)") exec "itemlist =" + item.action + "(item)" #Si no existe devuelve un error else: logger.info("No se ha encontrado la accion [" + item.action + "] en el canal [" + item.channel + "] ni en el launcher") #Llegados a este punto ya tenemos que tener el itemlist con los resultados correspondientes #Pueden darse 3 escenarios distintos: # 1. la función ha generado resultados y estan en el itemlist # 2. la función no ha generado resultados y por tanto el itemlist contiene 0 items, itemlist = [] # 3. la función realiza alguna accion con la cual no se generan nuevos items, en ese caso el resultado deve ser: itemlist = None para que no modifique el listado #A partir de aquí ya se ha ejecutado la funcion en el lugar adecuado, si queremos realizar alguna acción sobre los resultados, este es el lugar. #Filtrado de Servers if item.action == "findvideos": itemlist = servertools.filter_servers(itemlist) #Si la accion no ha devuelto ningún resultado, añade un item con el texto "No hay elementos para mostrar" if type(itemlist) == list: if len(itemlist) == 0: itemlist = [ Item( title="No hay elementos para mostrar", thumbnail= "http://media.tvalacarta.info/pelisalacarta/thumb_error.png" ) ] #Imprime en el log el resultado PrintItems(itemlist) #Muestra los resultados en pantalla platformtools.render_items(itemlist, item)
def render_items(self, itemlist, parent_item): """ Función encargada de mostrar el itemlist, se pasa como parametros el itemlist y el item del que procede @type itemlist: list @param itemlist: lista de elementos a mostrar @type parent_item: item @param parent_item: elemento padre """ # Si el itemlist no es un list salimos if not type(itemlist) == list: JsonData = {} JsonData["action"] = "HideLoading" JsonData["data"] = {} self.send_message(JsonData) return # Si no hay ningun item, mostramos un aviso if not len(itemlist): itemlist.append(Item(title="No hay elementos que mostrar")) if parent_item.channel == "channelselector" and not parent_item.action == "filterchannels": parent_item.viewmode = "banner" elif parent_item.channel == "channelselector" and parent_item.action == "filterchannels": parent_item.viewmode = "channel" #Item Atrás if not (parent_item.channel == "channelselector" and parent_item.action == "mainlist") and not itemlist[0].action == "go_back": if parent_item.viewmode in ["banner", "channel"]: itemlist.insert( 0, Item(title="Atrás", action="go_back", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "bannermenu", "thumb_atras.png"))) else: itemlist.insert( 0, Item(title="Atrás", action="go_back", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "squares", "thumb_atras.png"))) JsonData = {} JsonData["action"] = "EndItems" JsonData["data"] = {} JsonData["data"]["itemlist"] = [] JsonData["data"]["viewmode"] = parent_item.viewmode JsonData["data"]["category"] = parent_item.category.capitalize() JsonData["data"]["host"] = self.controller.host # Recorremos el itemlist for item in itemlist: if not item.thumbnail and item.action == "search": item.thumbnail = config.get_thumbnail_path( ) + "thumb_buscar.png" if not item.thumbnail and item.folder == True: item.thumbnail = "http://media.tvalacarta.info/pelisalacarta/thumb_folder.png" if not item.thumbnail and item.folder == False: item.thumbnail = "http://media.tvalacarta.info/pelisalacarta/thumb_nofolder.png" if "http://media.tvalacarta.info/" in item.thumbnail and not item.thumbnail.startswith( "http://media.tvalacarta.info/pelisalacarta/thumb_"): if parent_item.viewmode in ["banner", "channel"]: item.thumbnail = config.get_thumbnail_path( "bannermenu") + os.path.basename(item.thumbnail) else: item.thumbnail = config.get_thumbnail_path( ) + os.path.basename(item.thumbnail) #Estas imagenes no estan en bannermenu, asi que si queremos bannermenu, para que no se vean mal las quitamos elif parent_item.viewmode in [ "banner", "channel" ] and item.thumbnail.startswith( "http://media.tvalacarta.info/pelisalacarta/thumb_"): item.thumbnail = "" # Si el item no contiene categoria,le ponemos la del item padre if item.category == "": item.category = parent_item.category # Si el item no contiene fanart,le ponemos la del item padre if item.fanart == "": item.fanart = parent_item.fanart title = item.title.replace(" ", " ") # Formatear titulo if item.text_color: title = '[COLOR %s]%s[/COLOR]' % (item.text_color, title) if item.text_blod: title = '[B]%s[/B]' % title if item.text_italic: title = '[I]%s[/I]' % title matches = re.compile("(\[I\])(?:.*?)(\[\/I\])").findall(title) for match in matches: title = title.replace(match[0], "<i>").replace(match[1], "</i>") matches = re.compile("(\[B\])(?:.*?)(\[\/B\])").findall(title) for match in matches: title = title.replace(match[0], "<b>").replace(match[1], "</b>") matches = re.compile( "(\[COLOR ([^\]]+)\])(?:.*?)(\[\/COLOR\])").findall(title) for match in matches: title = title.replace(match[0], "<span style='color:" + match[1] + "'>").replace(match[2], "</span>") JsonItem = {} JsonItem["title"] = title JsonItem["thumbnail"] = item.thumbnail JsonItem["fanart"] = item.fanart JsonItem["plot"] = item.plot JsonItem["action"] = item.action JsonItem["url"] = item.tourl() JsonItem["context"] = [] if not item.action == "go_back": for Comando in self.set_context_commands(item, parent_item): JsonItem["context"].append({ "title": Comando[0], "url": Comando[1] }) JsonData["data"]["itemlist"].append(JsonItem) ID = self.send_message(JsonData) self.get_data(ID)
def addchannel(item): import os import time logger.info() tecleado = platformtools.dialog_input("", "Introduzca la URL") if not tecleado: return logger.info("url=%s" % tecleado) local_folder = config.get_runtime_path() if "canal" in item.title: local_folder = filetools.join(local_folder, 'channels') folder_to_extract = "channels" info_accion = "canal" else: local_folder = filetools.join(local_folder, 'servers') folder_to_extract = "servers" info_accion = "conector" # Detecta si es un enlace a un .py o .xml (pensado sobre todo para enlaces de github) try: extension = tecleado.rsplit(".", 1)[1] except: extension = "" files = [] zip = False if extension == "py" or extension == "xml": filename = tecleado.rsplit("/", 1)[1] localfilename = filetools.join(local_folder, filename) files.append([tecleado, localfilename, filename]) else: import re from core import scrapertools # Comprueba si la url apunta a una carpeta completa (channels o servers) de github if re.search(r'https://github.com/[^\s]+/'+folder_to_extract, tecleado): try: data = scrapertools.downloadpage(tecleado) matches = scrapertools.find_multiple_matches(data, '<td class="content">.*?href="([^"]+)".*?title="([^"]+)"') for url, filename in matches: url = "https://raw.githubusercontent.com" + url.replace("/blob/", "/") localfilename = filetools.join(local_folder, filename) files.append([url, localfilename, filename]) except: import traceback logger.error("Detalle del error: %s" % traceback.format_exc()) platformtools.dialog_ok("Error", "La url no es correcta o no está disponible") return else: filename = 'new%s.zip' % info_accion localfilename = filetools.join(config.get_data_path(), filename) files.append([tecleado, localfilename, filename]) zip = True logger.info("localfilename=%s" % localfilename) logger.info("descarga fichero...") try: if len(files) > 1: lista_opciones = ["No", "Sí", "Sí (Sobrescribir todos)"] overwrite_all = False from core import downloadtools for url, localfilename, filename in files: result = downloadtools.downloadfile(url, localfilename, continuar=False, resumir=False) if result == -3: if len(files) == 1: dyesno = platformtools.dialog_yesno("El archivo ya existe", "Ya existe el %s %s. " "¿Desea sobrescribirlo?" % (info_accion, filename)) else: if not overwrite_all: dyesno = platformtools.dialog_select("El archivo %s ya existe, ¿desea sobrescribirlo?" % filename, lista_opciones) else: dyesno = 1 # Diálogo cancelado if dyesno == -1: return # Caso de carpeta github, opción sobrescribir todos elif dyesno == 2: overwrite_all = True elif dyesno: hora_folder = "Copia seguridad [%s]" % time.strftime("%d-%m_%H-%M", time.localtime()) backup = filetools.join(config.get_data_path(), 'backups', hora_folder, folder_to_extract) if not filetools.exists(backup): os.makedirs(backup) import shutil shutil.copy2(localfilename, filetools.join(backup, filename)) downloadtools.downloadfile(url, localfilename, continuar=True, resumir=False) else: if len(files) == 1: return else: continue except: import traceback logger.error("Detalle del error: %s" % traceback.format_exc()) return if zip: try: # Lo descomprime logger.info("descomprime fichero...") from core import ziptools unzipper = ziptools.ziptools() logger.info("destpathname=%s" % local_folder) unzipper.extract(localfilename, local_folder, folder_to_extract, True, True) except: import traceback logger.error("Detalle del error: %s" % traceback.format_exc()) # Borra el zip descargado filetools.remove(localfilename) platformtools.dialog_ok("Error", "Se ha producido un error extrayendo el archivo") return # Borra el zip descargado logger.info("borra fichero...") filetools.remove(localfilename) logger.info("...fichero borrado") platformtools.dialog_ok("Éxito", "Actualización/Instalación realizada correctamente")
def getmainlist(preferred_thumb=""): logger.info("channelselector.getmainlist") itemlist = list() # Añade los canales que forman el menú principal itemlist.append( Item(title=config.get_localized_string(30119), channel="channelselector", action="getchanneltypes", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "main_menu_category.png"), viewmode="movie")) itemlist.append( Item(title=config.get_localized_string(30137), channel="buscadorall", action="mainlist", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "main_menu_search.png"), viewmode="movie")) itemlist.append( Item(title=config.get_localized_string(50002), channel="novedades", action="mainlist", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "thumb_novedades.png"), viewmode="movie")) itemlist.append( Item(title=config.get_localized_string(30102), channel="favoritos", action="mainlist", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "main_menu_fav.png"), viewmode="movie")) if config.get_library_support(): itemlist.append( Item(title=config.get_localized_string(30131), channel="biblioteca", action="mainlist", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "main_menu_library.png"), viewmode="movie")) #itemlist.append( Item(title=config.get_localized_string(30101) , channel="descargas" , action="mainlist", thumbnail = os.path.join(config.get_runtime_path() , "resources" , "images", "main_menu_download.png"),viewmode="movie") ) if "xbmceden" in config.get_platform(): itemlist.append( Item(title=config.get_localized_string(30100), channel="configuracion", action="mainlist", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "main_menu_conf.png"), folder=False, viewmode="movie")) else: itemlist.append( Item(title=config.get_localized_string(30100), channel="configuracion", action="mainlist", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "main_menu_conf.png"), viewmode="movie")) itemlist.append( Item(title=config.get_localized_string(30138), channel="update_version", action="update_from_menu", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "main_menu_download.png"), viewmode="movie")) itemlist.append( Item(title=config.get_localized_string(30104), channel="ayuda", action="mainlist", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "main_menu_help.png"), viewmode="movie")) return itemlist
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 search_results = Queue.Queue() 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 in ["", "true"]: # Buscar en la configuracion del canal include_in_global_search = str( config.get_setting("include_in_global_search", basename_without_extension)) # Si no hay valor en la configuración del canal se incluye ya que así estaba por defecto '''if include_in_global_search == "": include_in_global_search = "true"''' if include_in_global_search.lower() != "true": continue t = Thread( target=channel_search, args=[search_results, channel_parameters, category, tecleado]) t.setDaemon(True) t.start() number_of_channels += 1 start_time = int(time.time()) completed_channels = 0 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
from core import config from core import scrapertools from core.item import Item from servers import servertools #from pelisalacarta import buscador __channel__ = "filesmonster_catalogue" __category__ = "D" __type__ = "generic" __title__ = "filesmonster_catalogue" __language__ = "ES" DEBUG = config.get_setting("debug") IMAGES_PATH = os.path.join(config.get_runtime_path(), 'resources', 'images', 'filesmonster_catalogue') def strip_tags(value): return re.sub(r'<[^>]*?>', '', value) def isGeneric(): return True def mainlist(item): logger.info("[filesmonster_catalogue.py] mainlist") itemlist = []
logger.info("streamondemand-pureita.library_service serie=" + serie) serie = serie.split(",") ruta = os.path.join(config.get_library_path(), "SERIES", serie[0]) logger.info("streamondemand-pureita.library_service ruta =#" + ruta + "#") if os.path.exists(ruta): logger.info( "streamondemand-pureita.library_service Actualizando " + serie[0]) item = Item(url=serie[1], show=serie[0]) try: itemlist = [] pathchannels = os.path.join(config.get_runtime_path(), 'channels', serie[2].strip() + '.py') logger.info( "streamondemand-pureita.library_service Cargando canal " + pathchannels + " " + serie[2].strip()) obj = imp.load_source(serie[2].strip(), pathchannels) itemlist = obj.episodios(item) except: import traceback logger.error(traceback.format_exc()) itemlist = [] else: logger.info( "streamondemand-pureita.library_service No actualiza " +
# -*- coding: iso-8859-1 -*- #------------------------------------------------------------ # tvalacarta # XBMC (pre-dharma) entry point # http://blog.tvalacarta.info/plugin-xbmc/tvalacarta/ #------------------------------------------------------------ # Constants __plugin__ = "tvalacarta" __author__ = "tvalacarta" __url__ = "http://blog.tvalacarta.info/plugin-xbmc/tvalacarta/" __date__ = "02 Enero 2013" __version__ = "3.3.20" import os import sys from core import config from core import logger logger.info("[default.py] tvalacarta init...") librerias = xbmc.translatePath( os.path.join( config.get_runtime_path(), 'lib' ) ) sys.path.append (librerias) # Runs xbmc launcher from platformcode.xbmc import launcher launcher.run()
def do_search(item): logger.info("streamondemand.channels.buscador do_search") tecleado = item.extra mostra = item.fulltitle itemlist = [] import os import glob import imp from lib.fuzzywuzzy import fuzz import threading import Queue import time import re master_exclude_data_file = os.path.join(config.get_runtime_path(), "resources", "sodsearch.txt") logger.info("streamondemand.channels.buscador master_exclude_data_file=" + master_exclude_data_file) channels_path = os.path.join(config.get_runtime_path(), "channels", '*.py') logger.info("streamondemand.channels.buscador channels_path=" + channels_path) excluir = "" if os.path.exists(master_exclude_data_file): logger.info( "streamondemand.channels.buscador Encontrado fichero exclusiones") fileexclude = open(master_exclude_data_file, "r") excluir = fileexclude.read() fileexclude.close() else: logger.info( "streamondemand.channels.buscador No encontrado fichero exclusiones" ) excluir = "seriesly\nbuscador\ntengourl\n__init__" if config.is_xbmc(): show_dialog = True try: import xbmcgui progreso = xbmcgui.DialogProgressBG() progreso.create("Ricerca di " + mostra) except: show_dialog = False def worker(infile, queue): channel_result_itemlist = [] try: basename_without_extension = os.path.basename(infile)[:-3] # http://docs.python.org/library/imp.html?highlight=imp#module-imp obj = imp.load_source(basename_without_extension, infile) logger.info("streamondemand.channels.buscador cargado " + basename_without_extension + " de " + infile) channel_result_itemlist.extend(obj.search(Item(), tecleado)) for item in channel_result_itemlist: item.title = " [COLOR azure] " + item.title + " [/COLOR] [COLOR orange]su[/COLOR] [COLOR green]" + basename_without_extension + "[/COLOR]" item.viewmode = "list" except: import traceback logger.error(traceback.format_exc()) queue.put(channel_result_itemlist) channel_files = [ infile for infile in glob.glob(channels_path) if os.path.basename(infile)[:-3] not in excluir ] result = Queue.Queue() threads = [ threading.Thread(target=worker, args=(infile, result)) for infile in channel_files ] start_time = int(time.time()) for t in threads: t.daemon = True # NOTE: setting dameon to True allows the main thread to exit even if there are threads still running t.start() number_of_channels = len(channel_files) completed_channels = 0 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 if show_dialog: progreso.update(completed_channels * 100 / number_of_channels) try: result_itemlist = result.get(timeout=timeout) completed_channels += 1 except: # Expired timeout raise an exception break for item in result_itemlist: title = item.fulltitle # Clean up a bit the returned title to improve the fuzzy matching title = re.sub(r'\(.*\)', '', title) # Anything within () title = re.sub(r'\[.*\]', '', title) # Anything within [] # Check if the found title fuzzy matches the searched one if fuzz.WRatio(mostra, title) > 85: itemlist.append(item) if show_dialog: progreso.close() itemlist = sorted(itemlist, key=lambda item: item.fulltitle) return itemlist
def do_channels_search(item): logger.info("streamondemand-pureita.channels.biblioteca do_channels_search") try: title_year = int(item.extra[0:4]) except: title_year = 0 mostra = item.extra[4:] tecleado = urllib.quote_plus(mostra) itemlist = [] channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml') logger.info("streamondemand-pureita.channels.buscador channels_path=" + channels_path) channel_language = config.get_setting("channel_language") logger.info("streamondemand-pureita.channels.buscador channel_language=" + channel_language) if channel_language == "": channel_language = "all" logger.info("streamondemand-pureita.channels.buscador channel_language=" + channel_language) if config.is_xbmc(): show_dialog = True try: import xbmcgui progreso = xbmcgui.DialogProgressBG() progreso.create(NLS_Looking_For % mostra) except: show_dialog = False def worker(infile, queue): channel_result_itemlist = [] try: basename_without_extension = os.path.basename(infile)[:-4] # http://docs.python.org/library/imp.html?highlight=imp#module-imp obj = imp.load_source(basename_without_extension, infile[:-4]+".py") logger.info("streamondemand-pureita.channels.buscador cargado " + basename_without_extension + " de " + infile) # item.url contains search type: serie, anime, etc... channel_result_itemlist.extend(obj.search(Item(extra=item.url), tecleado)) for local_item in channel_result_itemlist: local_item.title = " [COLOR azure] " + local_item.title + " [/COLOR] [COLOR orange]su[/COLOR] [COLOR orange]" + basename_without_extension + "[/COLOR]" local_item.viewmode = "list" except: import traceback logger.error(traceback.format_exc()) queue.put(channel_result_itemlist) channel_files = glob.glob(channels_path) channel_files_tmp = [] for infile in channel_files: basename_without_extension = os.path.basename(infile)[:-4] channel_parameters = channeltools.get_channel_parameters(basename_without_extension) # Non cercare se il canale e inattivo if channel_parameters["active"] != "true": continue # Non cercare se un canale e escluso dalla ricerca globale if channel_parameters["include_in_global_search"] != "true": continue # Non cercare se un canale e per adulti e la modalita adulta disabilitata if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "false": continue # Non cercare se un canale ha il filtro lingua if channel_language != "all" and channel_parameters["language"] != channel_language: continue channel_files_tmp.append(infile) channel_files = channel_files_tmp result = Queue.Queue() threads = [threading.Thread(target=worker, args=(infile, result)) for infile in channel_files] start_time = int(time.time()) for t in threads: t.daemon = True # NOTE: setting dameon to True allows the main thread to exit even if there are threads still running t.start() number_of_channels = len(channel_files) completed_channels = 0 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 if show_dialog: progreso.update(completed_channels * 100 / number_of_channels) try: result_itemlist = result.get(timeout=timeout) completed_channels += 1 except: # Expired timeout raise an exception break for item in result_itemlist: title = item.fulltitle # If the release year is known, check if it matches the year found in the title if title_year > 0: year_match = re.search('\(.*(\d{4}).*\)', title) if year_match and abs(int(year_match.group(1)) - title_year) > 1: continue # Clean up a bit the returned title to improve the fuzzy matching title = re.sub(r'\(.*\)', '', title) # Anything within () title = re.sub(r'\[.*\]', '', title) # Anything within [] # Check if the found title fuzzy matches the searched one if fuzz.token_sort_ratio(mostra, title) > 85: itemlist.append(item) if show_dialog: progreso.close() itemlist = sorted(itemlist, key=lambda item: item.fulltitle) return itemlist
import sys from socket import gaierror from core import config from core import logger from core import scrapertools from platformcode import platformtools try: from lib.sambatools import libsmb as samba except ImportError: try: import xbmc librerias = xbmc.translatePath( os.path.join(config.get_runtime_path(), 'lib')) except ImportError: xbmc = None librerias = os.path.join(config.get_runtime_path(), 'lib') sys.path.append(librerias) from sambatools import libsmb as samba def remove_chars(path): """ Elimina cáracteres no permitidos @param path: cadena a validar @type path: str @rtype: str @return: devuelve la cadena sin los caracteres no permitidos
def start(self, list_controls=None, dict_values=None, caption="", callback=None, item=None, custom_button=None, channelpath=None): logger.info() # Ruta para las imagenes de la ventana self.mediapath = os.path.join(config.get_runtime_path(), 'resources', 'skins', 'Default', 'media') # Capturamos los parametros self.list_controls = list_controls self.values = dict_values self.caption = caption self.callback = callback self.item = item if type(custom_button) == dict: self.custom_button = {} self.custom_button["label"] = custom_button.get("label", "") self.custom_button["function"] = custom_button.get("function", "") self.custom_button["visible"] = bool(custom_button.get("visible", True)) self.custom_button["close"] = bool(custom_button.get("close", False)) else: self.custom_button = None # Obtenemos el canal desde donde se ha echo la llamada y cargamos los settings disponibles para ese canal if not channelpath: channelpath = inspect.currentframe().f_back.f_back.f_code.co_filename self.channel = os.path.basename(channelpath).replace(".py", "") self.ch_type = os.path.basename(os.path.dirname(channelpath)) # Si no tenemos list_controls, hay que sacarlos del json del canal if not self.list_controls: # Si la ruta del canal esta en la carpeta "channels", obtenemos los controles y valores mediante chaneltools if os.path.join(config.get_runtime_path(), "channels") in channelpath: # La llamada se hace desde un canal self.list_controls, default_values = channeltools.get_channel_controls_settings(self.channel) self.kwargs = {"channel": self.channel} # Si la ruta del canal esta en la carpeta "servers", obtenemos los controles y valores mediante servertools elif os.path.join(config.get_runtime_path(), "servers") in channelpath: # La llamada se hace desde un canal self.list_controls, default_values = servertools.get_server_controls_settings(self.channel) self.kwargs = {"server": self.channel} # En caso contrario salimos else: return None # Si no se pasan dict_values, creamos un dict en blanco if self.values is None: self.values = {} # Ponemos el titulo if self.caption == "": self.caption = str(config.get_localized_string(30100)) + " -- " + self.channel.capitalize() elif self.caption.startswith('@') and unicode(self.caption[1:]).isnumeric(): self.caption = config.get_localized_string(int(self.caption[1:])) # Muestra la ventana self.return_value = None self.doModal() return self.return_value
# -*- coding: utf-8 -*- # ------------------------------------------------------------ # streamondemand - XBMC Plugin # Acceso a directorios con samba # http://www.mimediacenter.info/foro/viewforum.php?f=36 # ------------------------------------------------------------ import os import sys from core import config from core import logger try: import xbmc librerias = xbmc.translatePath( os.path.join(config.get_runtime_path(), 'lib', 'sambatools')) except ImportError: xbmc = None librerias = os.path.join(config.get_runtime_path(), 'lib', 'sambatools') if librerias not in sys.path: sys.path.append(librerias) def parse_url(url): logger.info("[lib.samba.py] url=" + url) # Algunas trampas para facilitar el parseo de la url url = url.strip() if not url.endswith("/"): url += "/"
def getchanneltypes(preferred_thumb=""): logger.info() # Ahora construye el itemlist ordenadamente itemlist = list() itemlist.append( Item(title="Top Channels", channel="channelselector", action="filterchannels", category="top channels", channel_type="top channels", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "cat_menu_topchannels.png"), viewmode="movie")) itemlist.append( Item(title=config.get_localized_string(30122), channel="channelselector", action="filterchannels", category="movie", channel_type="movie", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "cat_menu_film.png"), viewmode="movie")) itemlist.append( Item(title=config.get_localized_string(30123), channel="channelselector", action="filterchannels", category="serie", channel_type="serie", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "cat_menu_series.png"), viewmode="movie")) itemlist.append( Item(title=config.get_localized_string(30124), channel="channelselector", action="filterchannels", category="anime", channel_type="anime", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "cat_menu_anime.png"), viewmode="movie")) itemlist.append( Item(title=config.get_localized_string(30125), channel="channelselector", action="filterchannels", category="documentary", channel_type="documentary", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "cat_menu_documentales.png"), viewmode="movie")) itemlist.append( Item(title="Cult", channel="channelselector", action="filterchannels", category="cult", channel_type="cult", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "main_menu_filmontv.png"), viewmode="movie")) itemlist.append( Item(title=config.get_localized_string(50000), channel="saghe", action="mainlist", category="saghe", channel_type="saghe", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "cat_menu_saghe.png"))) itemlist.append( Item(title=config.get_localized_string(50001), channel="filmontv", action="mainlist", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "main_menu_filmontv.png"), viewmode="movie")) #itemlist.append( Item(title=config.get_localized_string(50003) , channel="netflixsrc" , action="mainlist" , thumbnail = os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_series.png"),viewmode="movie") ) itemlist.append( Item(title=config.get_localized_string(30136), channel="channelselector", action="filterchannels", channel_type="vos", category="vos", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "cat_menu_vos.png"), viewmode="movie")) #itemlist.append( Item( title="Torrent" , channel="channelselector" , action="filterchannels" , channel_type="torrent", category="torrent" , thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_torrent.png"),viewmode="movie") ) itemlist.append( Item(title="[COLOR yellow]" + config.get_localized_string(30121) + "[/COLOR]", channel="channelselector", action="filterchannels", channel_type="all", category="all", thumbnail=os.path.join(config.get_runtime_path(), "resources", "images", "main_menu_all.png"), viewmode="movie")) return itemlist