コード例 #1
0
def findvideos(item):
    from core import servertools

    if item.infoLabels["tmdb_id"]:
        tmdb.set_infoLabels_item(item, __modo_grafico__)

    data = httptools.downloadpage(item.url).data
    iframe = scrapertools.find_single_match(data, '<iframe src="([^"]+)"')
    if "goo.gl/" in iframe:
        data += httptools.downloadpage(iframe,
                                       follow_redirects=False,
                                       only_headers=True).headers.get(
                                           "location", "")
    itemlist = servertools.find_video_items(item, data)

    library_path = config.get_library_path()
    if config.get_library_support():
        title = "Añadir película a la biblioteca"
        if item.infoLabels["imdb_id"] and not library_path.lower().startswith(
                "smb://"):
            try:
                from core import filetools
                movie_path = filetools.join(config.get_library_path(), 'CINE')
                files = filetools.walk(movie_path)
                for dirpath, dirname, filename in files:
                    for f in filename:
                        if item.infoLabels["imdb_id"] in f and f.endswith(
                                ".nfo"):
                            from core import library
                            head_nfo, it = library.read_nfo(
                                filetools.join(dirpath, dirname, f))
                            canales = it.library_urls.keys()
                            canales.sort()
                            if "clasicofilm" in canales:
                                canales.pop(canales.index("clasicofilm"))
                                canales.insert(
                                    0, "[COLOR red]clasicofilm[/COLOR]")
                            title = "Película ya en tu biblioteca. [%s] ¿Añadir?" % ",".join(
                                canales)
                            break
            except:
                import traceback
                logger.error(traceback.format_exc())

        itemlist.append(
            item.clone(action="add_pelicula_to_library", title=title))

    token_auth = config.get_setting("token_trakt", "tvmoviedb")
    if token_auth and item.infoLabels["tmdb_id"]:
        itemlist.append(
            item.clone(channel="tvmoviedb",
                       title="[Trakt] Gestionar con tu cuenta",
                       action="menu_trakt",
                       extra="movie"))

    return itemlist
コード例 #2
0
ファイル: clasicofilm.py プロジェクト: prosich/pelisalacarta
def findvideos(item):
    from core import servertools

    if item.infoLabels["tmdb_id"]:
        tmdb.set_infoLabels_item(item, __modo_grafico__)

    itemlist = servertools.find_video_items(item)

    library_path = config.get_library_path()
    if config.get_library_support():
        title = "Añadir película a la biblioteca"
        if item.infoLabels["imdb_id"] and not library_path.lower().startswith(
                "smb://"):
            try:
                from core import filetools
                movie_path = filetools.join(config.get_library_path(), 'CINE')
                files = filetools.walk(movie_path)
                for dirpath, dirname, filename in files:
                    for f in filename:
                        if item.infoLabels["imdb_id"] in f and f.endswith(
                                ".nfo"):
                            from core import library
                            head_nfo, it = library.read_nfo(
                                filetools.join(dirpath, dirname, f))
                            canales = it.library_urls.keys()
                            canales.sort()
                            if "clasicofilm" in canales:
                                canales.pop(canales.index("clasicofilm"))
                                canales.insert(
                                    0, "[COLOR red]clasicofilm[/COLOR]")
                            title = "Película ya en tu biblioteca. [%s] ¿Añadir?" % ",".join(
                                canales)
                            break
            except:
                import traceback
                logger.info(traceback.format_exc())
                pass

        itemlist.append(
            item.clone(action="add_pelicula_to_library", title=title))

    token_auth = config.get_setting("token_trakt", "tvmoviedb")
    if token_auth and item.infoLabels["tmdb_id"]:
        itemlist.append(
            item.clone(channel="tvmoviedb",
                       title="[Trakt] Gestionar con tu cuenta",
                       action="menu_trakt",
                       extra="movie"))

    return itemlist
コード例 #3
0
def mark_season_as_watched_on_kodi(item, value=1):
    """
        marca toda la temporada como vista o no vista en la libreria de Kodi
        @type item: item
        @param item: elemento a marcar
        @type value: int
        @param value: >0 para visto, 0 para no visto
        """
    logger.info()
    # logger.debug("item:\n" + item.tostring('\n'))

    # Solo podemos marcar la temporada como vista en la BBDD de Kodi si la BBDD es local,
    # en caso de compartir BBDD esta funcionalidad no funcionara
    if config.get_setting("library_mode", "biblioteca"):
        return

    if value == 0:
        value = 'Null'

    request_season = ''
    if item.contentSeason > -1:
        request_season = ' and c12= %s' % item.contentSeason

    tvshows_path = filetools.join(config.get_library_path(), FOLDER_TVSHOWS)
    item_path1 = "%" + item.path.replace("\\\\", "\\").replace(
        tvshows_path, "")
    if item_path1[:-1] != "\\":
        item_path1 += "\\"
    item_path2 = item_path1.replace("\\", "/")

    sql = 'update files set playCount= %s where idFile  in ' \
          '(select idfile from episode_view where strPath like "%s" or strPath like "%s"%s)' % \
          (value, item_path1, item_path2, request_season)

    execute_sql_kodi(sql)
コード例 #4
0
def move_to_libray(item):

    download_path = filetools.join(config.get_setting("downloadpath"), item.downloadFilename)
    library_path = filetools.join(config.get_library_path(), *filetools.split(item.downloadFilename))
    final_path = download_path
      
    if config.get_setting("library_add", "descargas") == True and config.get_setting("library_move", "descargas") == True:   
      if not filetools.isdir(filetools.dirname(library_path)):
        filetools.mkdir(filetools.dirname(library_path))
    
      if filetools.isfile(library_path) and filetools.isfile(download_path) :
        filetools.remove(library_path)

      if filetools.isfile(download_path):
        if filetools.move(download_path, library_path):
          final_path = library_path
          
        if len(filetools.listdir(filetools.dirname(download_path))) == 0: 
          filetools.rmdir(filetools.dirname(download_path))
          
    if config.get_setting("library_add", "descargas") == True: 
      if filetools.isfile(final_path):
        if item.contentType == "movie" and item.infoLabels["tmdb_id"]:
          library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=final_path)
          library.save_library_movie(library_item)
          
        elif item.contentType == "episode" and item.infoLabels["tmdb_id"]:
          library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=final_path)
          tvshow = Item(channel= "descargas", contentType="tvshow", infoLabels = {"tmdb_id": item.infoLabels["tmdb_id"]})
          library.save_library_tvshow(tvshow, [library_item])
コード例 #5
0
def move_to_libray(item):
    # Copiamos el archivo a la biblioteca
    filetools.move(
        filetools.join(config.get_setting("downloadpath"),
                       item.downloadFilename),
        filetools.join(config.get_library_path(),
                       filetools.basename(item.downloadFilename)))
コード例 #6
0
def unzip(url):
    import zipfile
    
    # Path para guardar el zip como tem.zip los .torrent extraidos del zip
    torrents_path = config.get_library_path()+'/torrents'
    if not os.path.exists(torrents_path):
        os.mkdir(torrents_path)

    ## http://stackoverflow.com/questions/4028697/how-do-i-download-a-zip-file-in-python-using-urllib2
    # Open the url
    try:
        f = urllib2.urlopen(url)
        with open( torrents_path+"/temp.zip", "wb") as local_file:
            local_file.write(f.read())
        
        # Open our local file for writing
        fh = open(torrents_path+"/temp.zip", 'rb')
        z = zipfile.ZipFile(fh)
        for name in z.namelist():
            z.extract(name, torrents_path)
        fh.close()

    #handle errors
    except urllib2.HTTPError, e:
        print "HTTP Error:", e.code, url
コード例 #7
0
def mark_season_as_watched_on_kodi(item, value=1):
    """
        marca toda la temporada como vista o no vista en la libreria de Kodi
        @type item: item
        @param item: elemento a marcar
        @type value: int
        @param value: >0 para visto, 0 para no visto
        """
    logger.info()
    # logger.debug("item:\n" + item.tostring('\n'))

    # Solo podemos marcar la temporada como vista en la BBDD de Kodi si la BBDD es local,
    # en caso de compartir BBDD esta funcionalidad no funcionara
    if config.get_setting("library_mode", "biblioteca"):
        return

    if value == 0:
        value = 'Null'

    request_season = ''
    if item.contentSeason > -1:
        request_season = ' and c12= %s' % item.contentSeason

    tvshows_path = filetools.join(config.get_library_path(), FOLDER_TVSHOWS)
    item_path1 = "%" + item.path.replace("\\\\", "\\").replace(tvshows_path, "")
    if item_path1[:-1] != "\\":
        item_path1 += "\\"
    item_path2 = item_path1.replace("\\", "/")

    sql = 'update files set playCount= %s where idFile  in ' \
          '(select idfile from episode_view where strPath like "%s" or strPath like "%s"%s)' % \
          (value, item_path1, item_path2, request_season)

    execute_sql_kodi(sql)
コード例 #8
0
def unzip(url):
    import zipfile
    itemlist = []
    # Path para guardar el zip como tem.zip los .torrent extraidos del zip
    torrents_path = config.get_library_path() + '/torrents'

    if not os.path.exists(torrents_path):
        os.mkdir(torrents_path)

    ## http://stackoverflow.com/questions/4028697/how-do-i-download-a-zip-file-in-python-using-urllib2
    # Open the url
    try:
        f = urllib2.urlopen(url)
        with open(torrents_path + "/temp.zip", "wb") as local_file:
            local_file.write(f.read())

        # Open our local file for writing
        fh = open(torrents_path + "/temp.zip", 'rb')
        z = zipfile.ZipFile(fh)
        for name in z.namelist():
            z.extract(name, torrents_path)
        fh.close()

    #handle errors
    except urllib2.HTTPError, e:
        print "HTTP Error:", e.code, url
コード例 #9
0
ファイル: biblioteca.py プロジェクト: sodicarus/channels-1
def file(item):
    itemlist = []
    logger.info("[bibiolteca.py] file")
    logger.info("[biblioteca.py] urlfile--->>>" + item.url)

    risp = platformtools.dialog_select('Stream On Demand play video',
                                       ['Guarda', 'Rinomina', 'Elimina'])
    try:

        if risp == 0:
            xbmc.Player().play(item.url)

        elif risp == 1:
            nome = platformtools.dialog_input(item.fulltitle)
            os.renames(item.url, filetools.join(config.get_library_path(),
                                                nome))
            xbmc.executebuiltin("Container.Refresh")

        elif risp == 2:
            if elimina_file(item):
                filetools.remove(item.url)
                xbmc.executebuiltin("Container.Refresh")
    except:
        pass

    return itemlist
コード例 #10
0
def GuardarSerie(itemlist):
    # Progreso
    pDialog = xbmcgui.DialogProgress()
    ret = pDialog.create('pelisalacarta', 'Añadiendo episodios...')
    pDialog.update(0, 'Añadiendo episodio...')
    totalepisodes = len(itemlist)
    i = 0
    for item in itemlist:
        i = i + 1
        pDialog.update(i*100/totalepisodes, 'Añadiendo episodio...',item.title)
        
        if (pDialog.iscanceled()):
            return
        if item.action!="add_serie_to_library" and item.action!="download_all_episodes": 
            item.category='Series'
            item.action= 'play_from_library'
            Guardar(item)      
    pDialog.close()
    
    #Lista con series para actualizar
    nombre_fichero_listado_series = os.path.join( config.get_library_path() , "series.xml" )
    if not os.path.exists(nombre_fichero_listado_series):
        nombre_fichero_listado_series = os.path.join( config.get_data_path() , "series.xml" )

    #logger.info("nombre_fichero_listado_series="+nombre_fichero_listado_series)
    fichero_listado_series= open(nombre_fichero_listado_series.decode("utf8") ,"a")
    fichero_listado_series.write(LimpiarNombre(item.show)+"|"+item.url+"|"+item.channel+"\n")
    fichero_listado_series.flush()
    fichero_listado_series.close()
    
    ActualizarBiblioteca(item)
コード例 #11
0
def move_to_libray(item):
    try:
      from platformcode import library
    except:
      return
      
    # Copiamos el archivo a la biblioteca
    origen = filetools.join(config.get_setting("downloadpath"), item.downloadFilename)
    destino = filetools.join(config.get_library_path(), *filetools.split(item.downloadFilename))
    
    if not filetools.isdir(filetools.dirname(destino)):
      filetools.mkdir(filetools.dirname(destino))
    
    if filetools.isfile(destino) and filetools.isfile(origen) :
      filetools.remove(destino)

    if filetools.isfile(origen):
      filetools.move(origen, destino)
      if len(filetools.listdir(filetools.dirname(origen))) == 0: 
        filetools.rmdir(filetools.dirname(origen))
      
    else:
      logger.error("No se ha encontrado el archivo: %s" % origen)
    
    if filetools.isfile(destino):
      if item.contentType == "movie" and item.infoLabels["tmdb_id"]:
        library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=destino)
        
        library.save_library_movie(library_item)
        
      elif item.contentType == "episode" and item.infoLabels["tmdb_id"]:
        library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=destino)
        
        tvshow = Item(channel= "descargas", contentType="tvshow", infoLabels = {"tmdb_id": item.infoLabels["tmdb_id"]})
        library.save_library_tvshow(tvshow, [library_item])
コード例 #12
0
def elenco_file(item):
    logger.info("[biblioteca.py] elenco_file")
    itemlist=[]

    lista=filetools.listdir(config.get_library_path())

    for list in lista:
        if list.endswith(tuple(['.flv','.mp4','.avi','.mkv'])):
            itemlist.append(Item(channel=item.channel,
                                 action="file",
                                 title="[COLOR azure]" + list + "[/COLOR]",
                                 url=filetools.join(config.get_library_path(), list),
                                 thumbnail="",
                                 fanart="",
                                 fulltitle=list,
                                 show="",
                                 folder=False
                                 ))

    return itemlist
コード例 #13
0
ファイル: biblioteca.py プロジェクト: sodicarus/channels-1
def elenco_file(item):
    logger.info("[biblioteca.py] elenco_file")
    itemlist = []

    lista = filetools.listdir(config.get_library_path())

    for list in lista:
        if list.endswith(tuple(['.flv', '.mp4', '.avi', '.mkv'])):
            itemlist.append(
                Item(channel=item.channel,
                     action="file",
                     title="[COLOR azure]" + list + "[/COLOR]",
                     url=filetools.join(config.get_library_path(), list),
                     thumbnail="",
                     fanart="",
                     fulltitle=list,
                     show="",
                     folder=False))

    return itemlist
コード例 #14
0
ファイル: clasicofilm.py プロジェクト: CYBERxNUKE/xbmc-addon
def findvideos(item):
    from core import servertools

    if item.infoLabels["tmdb_id"]:
        tmdb.set_infoLabels_item(item, __modo_grafico__)

    itemlist = servertools.find_video_items(item)
    
    library_path = config.get_library_path()
    if config.get_library_support():
        title = "Añadir película a la biblioteca"
        if item.infoLabels["imdb_id"] and not library_path.lower().startswith("smb://"):
            try:
                from core import filetools
                movie_path = filetools.join(config.get_library_path(), 'CINE')
                files = filetools.walk(movie_path)
                for dirpath, dirname, filename in files:
                    for f in filename:
                        if item.infoLabels["imdb_id"] in f and f.endswith(".nfo"):
                            from core import library
                            head_nfo, it = library.read_nfo(filetools.join(dirpath, dirname, f))
                            canales = it.library_urls.keys()
                            canales.sort()
                            if "clasicofilm" in canales:
                                canales.pop(canales.index("clasicofilm"))
                                canales.insert(0, "[COLOR red]clasicofilm[/COLOR]")
                            title = "Película ya en tu biblioteca. [%s] ¿Añadir?" % ",".join(canales)
                            break
            except:
                import traceback
                logger.info(traceback.format_exc())
                pass
        
        itemlist.append(item.clone(action="add_pelicula_to_library", title=title))

    token_auth = config.get_setting("token_trakt", "tvmoviedb")
    if token_auth and item.infoLabels["tmdb_id"]:
        itemlist.append(item.clone(channel="tvmoviedb", title="[Trakt] Gestionar con tu cuenta", action="menu_trakt",
                                   extra="movie"))
    
    return itemlist
コード例 #15
0
def file_cine_library(item):
    import os
    from platformcode import library
    librarypath = os.path.join(config.get_library_path(),"CINE")
    archivo = library.title_to_folder_name(item.title.strip())
    strmfile = archivo+".strm"
    strmfilepath = os.path.join(librarypath,strmfile)

    if not os.path.exists(strmfilepath):
        itemlist.append( Item(channel=item.channel, title=">> Añadir a la biblioteca...", url=item.url, action="add_file_cine_library", extra="episodios", show=archivo) )

    return itemlist
コード例 #16
0
def file_cine_library(item):
    import os
    from platformcode.xbmc import library
    librarypath = os.path.join(config.get_library_path(),"CINE")
    archivo = library.title_to_folder_name(item.title.strip())
    strmfile = archivo+".strm"
    strmfilepath = os.path.join(librarypath,strmfile)

    if not os.path.exists(strmfilepath):
        itemlist.append( Item(channel=item.channel, title=">> Añadir a la biblioteca...", url=item.url, action="add_file_cine_library", extra="episodios", show=archivo) )

    return itemlist
コード例 #17
0
ファイル: hdfull.py プロジェクト: prosich/pelisalacarta
def file_cine_library(item,url_targets):
    import os
    from core import filetools
    librarypath = os.path.join(config.get_library_path(),"CINE")
    archivo = item.show.strip()
    strmfile = archivo+".strm"
    strmfilepath = filetools.join(librarypath,strmfile)

    if not os.path.exists(strmfilepath):
        itemlist = []
        itemlist.append( Item(channel=item.channel, title=">> Añadir a la biblioteca...", url=url_targets, action="add_file_cine_library", extra="episodios", show=archivo) )

    return itemlist
コード例 #18
0
ファイル: hdfull.py プロジェクト: jurrKodi/pelisalacarta
def file_cine_library(item,url_targets):
    import os
    from core import filetools
    librarypath = os.path.join(config.get_library_path(),"CINE")
    archivo = item.show.strip()
    strmfile = archivo+".strm"
    strmfilepath = filetools.join(librarypath,strmfile)

    if not os.path.exists(strmfilepath):
        itemlist = []
        itemlist.append( Item(channel=item.channel, title=">> Añadir a la biblioteca...", url=url_targets, action="add_file_cine_library", extra="episodios", show=archivo) )

    return itemlist
コード例 #19
0
ファイル: descargas.py プロジェクト: Dreancala/Prova
def move_to_libray(item):
    if not config.get_setting("library_move", "descargas") == True:
        return

    try:
        from core import library
    except:
        return

    # Copiamos el archivo a la biblioteca
    origen = filetools.join(config.get_setting("downloadpath"),
                            item.downloadFilename)
    destino = filetools.join(config.get_library_path(),
                             *filetools.split(item.downloadFilename))

    if not filetools.isdir(filetools.dirname(destino)):
        filetools.mkdir(filetools.dirname(destino))

    if filetools.isfile(destino) and filetools.isfile(origen):
        filetools.remove(destino)

    if filetools.isfile(origen):
        filetools.move(origen, destino)
        if len(filetools.listdir(filetools.dirname(origen))) == 0:
            filetools.rmdir(filetools.dirname(origen))

    else:
        logger.error("No se ha encontrado el archivo: %s" % origen)

    if filetools.isfile(destino):
        if item.contentType == "movie" and item.infoLabels["tmdb_id"]:
            library_item = Item(title="Scaricato: %s" % item.downloadFilename,
                                channel="descargas",
                                action="findvideos",
                                infoLabels=item.infoLabels,
                                url=item.downloadFilename)

            library.save_library_movie(library_item)

        elif item.contentType == "episode" and item.infoLabels["tmdb_id"]:
            library_item = Item(title="Scaricato: %s" % item.downloadFilename,
                                channel="descargas",
                                action="findvideos",
                                infoLabels=item.infoLabels,
                                url=item.downloadFilename)

            tvshow = Item(channel="descargas",
                          contentType="tvshow",
                          infoLabels={"tmdb_id": item.infoLabels["tmdb_id"]})
            library.save_library_tvshow(tvshow, [library_item])
コード例 #20
0
ファイル: library.py プロジェクト: kampanita/pelisalacarta
def library_in_kodi():
    """
    comprueba si la libreria de pelisalacarta está configurada en xbmc/Kodi
    @rtype:   bool
    @return:  si está configurada la libreria en xbmc/Kodi.
    """
    logger.info("pelisalacarta.platformcode.library library_in_kodi")
    # TODO arreglar
    return True

    path = xbmc.translatePath(os.path.join("special://profile/", "sources.xml"))
    data = read_file(path)

    if config.get_library_path() in data:
        return True
    else:
        return False
コード例 #21
0
ファイル: divxtotal.py プロジェクト: CYBERxNUKE/xbmc-addon
def ext_size(url):
     torrents_path = config.get_library_path()+'/torrents'
     if not os.path.exists(torrents_path):
        os.mkdir(torrents_path)
     try:
      urllib.urlretrieve("http://anonymouse.org/cgi-bin/anon-www.cgi/"+url, torrents_path+"/temp.torrent")
      pepe = open( torrents_path+"/temp.torrent", "rb").read()
     except:
      pepe=""
     
     torrent = decode(pepe)
     try:
      name = torrent["info"]["name"]
      sizet = torrent["info"]['length']
      sizet=convert_size(sizet)
     except:
        name = "no disponible"
     try:
      check_video = scrapertools.find_multiple_matches(str(torrent["info"]["files"]),"'length': (\d+)}")
      size=max([int(i) for i in check_video])
      for file in torrent["info"]["files"]:
         manolo = "%r - %d bytes" % ("/".join(file["path"]), file["length"])
         if str(size) in manolo:
             video= manolo
      size =convert_size(size)
      ext_v= re.sub(r"-.*? bytes|.*?\[.*?\].|'|.*?COM.|.*?\[.*?\]|\(.*?\)|.*?\.","",video)
      try:
       os.remove(torrents_path+"/temp.torrent")
      except:
       pass
     except:
      try:
        size = sizet
        ext_v= re.sub(r"-.*? bytes|.*?\[.*?\].|'|.*?COM.|.*?\.es.|.*?\[.*?\]|.*?\(.*?\)\.|.*?\.","",name)
      except:
        size = "NO REPRODUCIBLE"
        ext_v = ""
      try:
       os.remove(torrents_path+"/temp.torrent")
      except:
       pass
     if "rar" in ext_v:
        ext_v= ext_v +" -- No reproducible"
        size= ""
     return ext_v , size
コード例 #22
0
ファイル: divxtotal.py プロジェクト: d3v3l0p1n/mitvspain
def ext_size(url):
     torrents_path = config.get_library_path()+'/torrents'
     if not os.path.exists(torrents_path):
        os.mkdir(torrents_path)
     try:
      urllib.urlretrieve("http://anonymouse.org/cgi-bin/anon-www.cgi/"+url, torrents_path+"/temp.torrent")
      pepe = open( torrents_path+"/temp.torrent", "rb").read()
     except:
      pepe=""
     
     torrent = decode(pepe)
     try:
      name = torrent["info"]["name"]
      sizet = torrent["info"]['length']
      sizet=convert_size(sizet)
     except:
        name = "no disponible"
     try:
      check_video = scrapertools.find_multiple_matches(str(torrent["info"]["files"]),"'length': (\d+)}")
      size=max([int(i) for i in check_video])
      for file in torrent["info"]["files"]:
         manolo = "%r - %d bytes" % ("/".join(file["path"]), file["length"])
         if str(size) in manolo:
             video= manolo
      size =convert_size(size)
      ext_v= re.sub(r"-.*? bytes|.*?\[.*?\].|'|.*?COM.|.*?\[.*?\]|\(.*?\)|.*?\.","",video)
      try:
       os.remove(torrents_path+"/temp.torrent")
      except:
       pass
     except:
      try:
        size = sizet
        ext_v= re.sub(r"-.*? bytes|.*?\[.*?\].|'|.*?COM.|.*?\.es.|.*?\[.*?\]|.*?\(.*?\)\.|.*?\.","",name)
      except:
        size = "NO REPRODUCIBLE"
        ext_v = ""
      try:
       os.remove(torrents_path+"/temp.torrent")
      except:
       pass
     if "rar" in ext_v:
        ext_v= ext_v +" -- No reproducible"
        size= ""
     return ext_v , size
コード例 #23
0
def actualizarSerie(serie):    
    logger.info("[library_service.py] serie="+serie)
    global lista_nuevos_capitulos
    serie = serie.split("|")
    
    if multihilo:
        import threading
        #listahilos[threading.current_thread().name] ["serie"] =serie[0]
        msg= "[library_service.py] Actualizando "+serie[0]+" en hilo: "+ threading.current_thread().name
    else:
        msg= "[library_service.py] Actualizando "+serie[0]
    
    ruta = os.path.join( config.get_library_path() , "SERIES" , serie[0] )
    logger.info("[library_service.py] ruta =#"+ruta+"#")
    if os.path.exists( ruta ):
        logger.info(msg)
        item = Item(url=serie[1], show=serie[0])
        try:
            itemlist = []
            # Todos los canales que quieran actualizar sus series mediente este metodo
            # han de tener una funcion llamada 'episodios(item)' que retorna el listado de capitulos
            exec "import pelisalacarta.channels."+ serie[2].strip() +" as channel"
            itemlist = channel.episodios(item)
            lista_nuevos_capitulos.append(library.AddCapitulos(itemlist))
        except:
            import traceback
            from pprint import pprint
            exc_type, exc_value, exc_tb = sys.exc_info()
            lines = traceback.format_exception(exc_type, exc_value, exc_tb)
            for line in lines:
                line_splits = line.split("\n")
                for line_split in line_splits:
                    logger.error(line_split)
            itemlist = []
    else:
        logger.info("[library_service.py] No actualiza "+serie[0]+" (no existe el directorio)")
        itemlist=[]
コード例 #24
0
def file(item):
    itemlist = []
    logger.info("[bibiolteca.py] file")
    logger.info("[biblioteca.py] urlfile--->>>" + item.url)

    risp = platformtools.dialog_select('Stream On Demand play video', ['Guarda', 'Rinomina', 'Elimina'])
    try:

        if risp == 0:
            xbmc.Player().play(item.url)

        elif risp == 1:
            nome = platformtools.dialog_input(item.fulltitle)
            os.renames(item.url, filetools.join(config.get_library_path(), nome))
            xbmc.executebuiltin("Container.Refresh")

        elif risp == 2:
            if elimina_file(item):
                filetools.remove(item.url)
                xbmc.executebuiltin("Container.Refresh")
    except:
        pass

    return itemlist
コード例 #25
0
def GuardarSerie(itemlist):
    # Progreso
    pDialog = xbmcgui.DialogProgress()
    ret = pDialog.create('pelisalacarta', 'Añadiendo episodios...')
    pDialog.update(0, 'Añadiendo episodio...')
    totalepisodes = len(itemlist)
    i = 0
    for item in itemlist:
        i = i + 1
        pDialog.update(i * 100 / totalepisodes, 'Añadiendo episodio...',
                       item.title)

        if (pDialog.iscanceled()):
            return
        if item.action != "add_serie_to_library" and item.action != "download_all_episodes":
            item.category = 'Series'
            item.action = 'play_from_library'
            Guardar(item)
    pDialog.close()

    #Lista con series para actualizar
    nombre_fichero_listado_series = os.path.join(config.get_library_path(),
                                                 "series.xml")
    if not os.path.exists(nombre_fichero_listado_series):
        nombre_fichero_listado_series = os.path.join(config.get_data_path(),
                                                     "series.xml")

    #logger.info("nombre_fichero_listado_series="+nombre_fichero_listado_series)
    fichero_listado_series = open(nombre_fichero_listado_series.decode("utf8"),
                                  "a")
    fichero_listado_series.write(
        LimpiarNombre(item.show) + "|" + item.url + "|" + item.channel + "\n")
    fichero_listado_series.flush()
    fichero_listado_series.close()

    ActualizarBiblioteca(item)
コード例 #26
0
def get_next_items(item):

    plugintools.log("navigation.get_next_items item=" + item.tostring())

    try:
        # ----------------------------------------------------------------
        #  Main menu
        # ----------------------------------------------------------------
        if item.channel == "navigation":
            # --- Update channels list ---------------------------------------
            from core import config
            if item.action == "mainlist":
                plugintools.log("navigation.get_next_items Main menu")

                if config.get_setting("updatechannels") == "true":
                    try:
                        from core import updater
                        actualizado = updater.updatechannel("channelselector")

                        if actualizado:
                            import xbmcgui
                            advertencia = xbmcgui.Dialog()
                            advertencia.ok("tvalacarta",
                                           config.get_localized_string(30064))
                    except:
                        pass
            # ----------------------------------------------------------------

            if item.action == "mainlist":
                plugintools.log("navigation.get_next_items Main menu")
                itemlist = channelselector.getmainlist("bannermenu")

        elif item.channel == "channelselector":

            if item.action == "channeltypes":
                plugintools.log("navigation.get_next_items Channel types menu")
                itemlist = channelselector.getchanneltypes("bannermenu")

            elif item.action == "listchannels":
                plugintools.log("navigation.get_next_items Channel list menu")
                itemlist = channelselector.filterchannels(
                    item.category, "bannermenu")

        elif item.channel == "configuracion":
            plugintools.open_settings_dialog()
            return []

        else:

            if item.action == "":
                item.action = "mainlist"

            plugintools.log("navigation.get_next_items Channel code (" +
                            item.channel + "." + item.action + ")")

            # --- Update channels files --------------------------------------
            if item.action == "mainlist":
                from core import config
                if config.get_setting("updatechannels") == "true":
                    try:
                        from core import updater
                        actualizado = updater.updatechannel(item.channel)

                        if actualizado:
                            import xbmcgui
                            advertencia = xbmcgui.Dialog()
                            advertencia.ok("plugin", item.channel,
                                           config.get_localized_string(30063))
                    except:
                        pass
            # ----------------------------------------------------------------

            try:
                exec "import channels." + item.channel + " as channel"
            except:
                exec "import core." + item.channel + " as channel"

            from platformcode import xbmctools

            if item.action == "play":
                plugintools.log("navigation.get_next_items play")

                # Si el canal tiene una acción "play" tiene prioridad
                if hasattr(channel, 'play'):
                    plugintools.log(
                        "streamondemand-pureita.navigation.py Channel has its own 'play' method"
                    )
                    itemlist = channel.play(item)
                    if len(itemlist) > 0:
                        item = itemlist[0]

                        # FIXME: Este error ha que tratarlo de otra manera, al dar a volver sin ver el vídeo falla
                        try:
                            xbmctools.play_video(channel=item.channel,
                                                 server=item.server,
                                                 url=item.url,
                                                 category=item.category,
                                                 title=item.title,
                                                 thumbnail=item.thumbnail,
                                                 plot=item.plot,
                                                 extra=item.extra,
                                                 subtitle=item.subtitle,
                                                 video_password=item.password,
                                                 fulltitle=item.fulltitle,
                                                 Serie=item.show)
                        except:
                            pass

                    else:
                        import xbmcgui
                        ventana_error = xbmcgui.Dialog()
                        ok = ventana_error.ok("plugin",
                                              "Nessun File Da Riprodurre")
                else:
                    plugintools.log(
                        "streamondemand-pureita.navigation.py No channel 'play' method, executing core method"
                    )

                    # FIXME: Este error ha que tratarlo de otra manera, por al dar a volver sin ver el vídeo falla
                    # Mejor hacer el play desde la ventana
                    try:
                        xbmctools.play_video(channel=item.channel,
                                             server=item.server,
                                             url=item.url,
                                             category=item.category,
                                             title=item.title,
                                             thumbnail=item.thumbnail,
                                             plot=item.plot,
                                             extra=item.extra,
                                             subtitle=item.subtitle,
                                             video_password=item.password,
                                             fulltitle=item.fulltitle,
                                             Serie=item.show)
                    except:
                        pass

                return []

            elif item.action == "findvideos":
                plugintools.log("navigation.get_next_items findvideos")

                # Si el canal tiene una acción "findvideos" tiene prioridad
                if hasattr(channel, 'findvideos'):
                    plugintools.log(
                        "streamondemand-pureita.navigation.py Channel has its own 'findvideos' method"
                    )
                    itemlist = channel.findvideos(item)
                else:
                    itemlist = []

                if len(itemlist) == 0:
                    from servers import servertools
                    itemlist = servertools.find_video_items(item)

                if len(itemlist) == 0:
                    itemlist = [
                        Item(title="No se han encontrado vídeos",
                             thumbnail=os.path.join(
                                 plugintools.get_runtime_path(), "resources",
                                 "images", "thumb_error.png"))
                    ]
            # ---------------add_serie_to_library-----------
            elif item.action == "add_serie_to_library":
                plugintools.log(
                    "navigation.get_next_items add_serie_to_library")
                from platformcode import library
                import xbmcgui

                # Obtiene el listado desde el que se llamó
                action = item.extra

                # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
                if "###" in item.extra:
                    action = item.extra.split("###")[0]
                    item.extra = item.extra.split("###")[1]

                exec "itemlist = channel." + action + "(item)"

                # Progreso
                pDialog = xbmcgui.DialogProgress()
                ret = pDialog.create('streamondemand-pureita',
                                     'Añadiendo episodios...')
                pDialog.update(0, 'Añadiendo episodio...')
                totalepisodes = len(itemlist)
                plugintools.log("navigation.get_next_items Total Episodios:" +
                                str(totalepisodes))
                i = 0
                errores = 0
                nuevos = 0
                for item in itemlist:
                    i = i + 1
                    pDialog.update(i * 100 / totalepisodes,
                                   'Añadiendo episodio...', item.title)
                    plugintools.log(
                        "streamondemand-pureita.navigation.py add_serie_to_library, title="
                        + item.title)
                    if (pDialog.iscanceled()):
                        return

                    try:
                        #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
                        # Añade todos menos el que dice "Añadir esta serie..." o "Descargar esta serie..."
                        if item.action != "add_serie_to_library" and item.action != "download_all_episodes":
                            nuevos = nuevos + library.savelibrary(
                                titulo=item.title,
                                url=item.url,
                                thumbnail=item.thumbnail,
                                server=item.server,
                                plot=item.plot,
                                canal=item.channel,
                                category="Series",
                                Serie=item.show.strip(),
                                verbose=False,
                                accion="play_from_library",
                                pedirnombre=False,
                                subtitle=item.subtitle,
                                extra=item.extra)
                    except IOError:
                        import sys
                        for line in sys.exc_info():
                            logger.error("%s" % line)
                        plugintools.log(
                            "streamondemand-pureita.navigation.py Error al grabar el archivo "
                            + item.title)
                        errores = errores + 1

                pDialog.close()

                # Actualizacion de la biblioteca
                itemlist = []
                if errores > 0:
                    itemlist.append(
                        Item(
                            title=
                            "ERRORE, la serie NON si è aggiunta alla biblioteca o la fatto in modo incompleto"
                        ))
                    plugintools.log(
                        "navigation.get_next_items No se pudo añadir " +
                        str(errores) + " episodios")
                else:
                    itemlist.append(
                        Item(
                            title="La serie è stata aggiunta alla biblioteca"))
                    plugintools.log(
                        "navigation.get_next_items Ningún error al añadir " +
                        str(errores) + " episodios")

                # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
                #library.update(totalepisodes,errores,nuevos)
                #xbmctools.renderItems(itemlist, params, url, category)

                #Lista con series para actualizar
                from core import config
                nombre_fichero_config_canal = os.path.join(
                    config.get_library_path(), "series.xml")
                if not os.path.exists(nombre_fichero_config_canal):
                    nombre_fichero_config_canal = os.path.join(
                        config.get_data_path(), "series.xml")

                plugintools.log("nombre_fichero_config_canal=" +
                                nombre_fichero_config_canal)
                if not os.path.exists(nombre_fichero_config_canal):
                    f = open(nombre_fichero_config_canal, "w")
                else:
                    f = open(nombre_fichero_config_canal, "r")
                    contenido = f.read()
                    f.close()
                    f = open(nombre_fichero_config_canal, "w")
                    f.write(contenido)
                from platformcode import library
                f.write(
                    library.title_to_folder_name(item.show) + "," + item.url +
                    "," + item.channel + "\n")
                f.close()
                return itemlist
            # --------------------------------------------------------------------
            elif item.action == "download_all_episodes":
                plugintools.log(
                    "navigation.get_next_items download_all_episodes")
                download_all_episodes(item, channel)

#---------------------------------------------------------------------
            else:

                if item.action == "search":
                    tecleado = plugintools.keyboard_input()
                    if tecleado != "":
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item, tecleado)
                elif item.channel == "novedades" and item.action == "mainlist":
                    itemlist = channel.mainlist(item, "bannermenu")
                elif item.channel == "buscador" and item.action == "mainlist":
                    itemlist = channel.mainlist(item, "bannermenu")
                else:
                    exec "itemlist = channel." + item.action + "(item)"

                for loaded_item in itemlist:

                    if loaded_item.thumbnail == "":
                        if loaded_item.folder:
                            loaded_item.thumbnail = os.path.join(
                                plugintools.get_runtime_path(), "resources",
                                "images", "thumb_folder.png")
                        else:
                            loaded_item.thumbnail = os.path.join(
                                plugintools.get_runtime_path(), "resources",
                                "images", "thumb_nofolder.png")

                if len(itemlist) == 0:
                    itemlist = [
                        Item(title="Nessun Elemento Da Visualizzare",
                             thumbnail=os.path.join(
                                 plugintools.get_runtime_path(), "resources",
                                 "images", "thumb_error.png"))
                    ]

    except:
        import traceback
        plugintools.log("navigation.get_next_items " + traceback.format_exc())
        itemlist = [
            Item(title="Rimozione Effettuata - Riavviare",
                 thumbnail=os.path.join(plugintools.get_runtime_path(),
                                        "resources", "images",
                                        "thumb_error.png"))
        ]

    return itemlist
コード例 #27
0
ファイル: descargas.py プロジェクト: jurrKodi/pelisalacarta
def move_to_libray(item):
    # Copiamos el archivo a la biblioteca
    filetools.move(filetools.join(config.get_setting("downloadpath"), item.downloadFilename),
                   filetools.join(config.get_library_path(), filetools.basename(item.downloadFilename)))
コード例 #28
0
# ------------------------------------------------------------
# Common Library Tools
# ------------------------------------------------------------

import errno
import math

from core import config
from core import filetools
from core import logger
from core import scrapertools
from core import scraper
from core.item import Item
from platformcode import platformtools

LIBRARY_PATH = config.get_library_path()
if config.get_setting("folder_movies") != "":
    FOLDER_MOVIES = config.get_setting("folder_movies")
else:
    FOLDER_MOVIES = "CINE"  # config.get_localized_string(30072)
if config.get_setting("folder_tvshows") != "":
    FOLDER_TVSHOWS = config.get_setting("folder_tvshows")
else:
    FOLDER_TVSHOWS = "SERIES"  # config.get_localized_string(30073)
MOVIES_PATH = filetools.join(LIBRARY_PATH, FOLDER_MOVIES)
TVSHOWS_PATH = filetools.join(LIBRARY_PATH, FOLDER_TVSHOWS)
logger.info("LIBRARY_PATH (RAW): " + LIBRARY_PATH)
# logger.info("MOVIES_PATH (RAW): " + MOVIES_PATH)
# logger.info("TVSHOWS_PATH (RAW): " + TVSHOWS_PATH)
logger.info("FOLDER_MOVIES (RAW): " + FOLDER_MOVIES)
logger.info("FOLDER_TVSHOWS (RAW): " + FOLDER_TVSHOWS)
コード例 #29
0
import xbmc, time

from core import scrapertools
from core import config
from core import logger
from core.item import Item
from servers import servertools

logger.info("[library_service.py] Actualizando series...")
from platformcode.xbmc import library
from platformcode.xbmc import launcher
import xbmcgui

#Eliminar carpeta antes de actualizar

directorio = os.path.join(config.get_library_path(), "SERIES")
logger.info("directorio=" + directorio)
import shutil

#if os.path.exists(directorio):
#    shutil.rmtree(directorio)

if not os.path.exists(directorio):
    os.mkdir(directorio)

nombre_fichero_config_canal = os.path.join(config.get_data_path(),
                                           "series.xml")

try:

    if config.get_setting("updatelibrary") == "true":
コード例 #30
0
def peliculas(item):
    logger.info("pelisalacarta.channels.biblioteca peliculas")
    strm_path = library.MOVIES_PATH
    download_path = filetools.join(config.get_library_path(), "Descargas", "Cine")

    itemlist = []

    for raiz, subcarpetas, ficheros in filetools.walk(strm_path):
        for f in ficheros:
            if f.endswith(".strm"):
                i = filetools.join(raiz, f)

                movie = Item().fromurl(filetools.read(i))
                movie.contentChannel = movie.channel
                movie.path = i
                movie.title = os.path.splitext(os.path.basename(i))[0].capitalize()
                movie.channel = "biblioteca"
                movie.action = "findvideos"
                movie.text_color = "blue"
                # fix para que no se ejecute el método de play para la biblioteca de Kodi
                movie.strm = False

                itemlist.append(movie)

    # Obtenemos todos los videos de la biblioteca de CINE recursivamente
    for raiz, subcarpetas, ficheros in filetools.walk(download_path):
        for f in ficheros:
            if not f.endswith(".json") and not f.endswith(".nfo") and not f.endswith(".srt"):
                i = filetools.join(raiz, f)

                movie = Item()
                movie.contentChannel = "local"
                movie.path = i
                movie.title = os.path.splitext(os.path.basename(i))[0].capitalize()
                movie.channel = "biblioteca"
                movie.action = "play"
                movie.text_color = "green"

                itemlist.append(movie)

    library.set_infolabels_from_library(itemlist, tipo="Movies")

    # Agrupamos las peliculas por canales
    join_itemlist = []

    for i in range(len(itemlist)):
        encontrado = False
        for j in range(i + 1, len(itemlist)):
            if "tmdb_id" in itemlist[i].infoLabels and "tmdb_id" in itemlist[j].infoLabels:
                if itemlist[i].infoLabels["tmdb_id"] == itemlist[j].infoLabels["tmdb_id"]:
                    encontrado = True

                    if "list_channels" not in itemlist[i]:
                        list_channels = []
                        dict_first_channel = {"path": itemlist[i].path, "channel": itemlist[i].contentChannel}
                        list_channels.append(dict_first_channel.copy())
                        itemlist[j].list_channels = list_channels

                    dict_other_channel = {"path": itemlist[j].path, "channel": itemlist[j].contentChannel}
                    itemlist[j].list_channels.append(dict_other_channel.copy())
                    itemlist[j].action = "get_canales_movies"
                    itemlist[j].text_color = "orange"

        # TODO pendiente de probar
        if "contentTitle" in itemlist[i] and itemlist[i].contentTitle != "":
            itemlist[i].title = itemlist[i].contentTitle

        if not encontrado:
            join_itemlist.append(itemlist[i])

    return sorted(join_itemlist, key=lambda it: it.title.lower())
コード例 #31
0
import sys
import xbmc,time

from core import scrapertools
from core import config
from core import logger
from core.item import Item
from servers import servertools

logger.info("pelisalacarta.library_service Actualizando series...")
from platformcode import library
from platformcode import launcher
import xbmcgui
import imp

directorio = os.path.join(config.get_library_path(),"SERIES")
logger.info ("directorio="+directorio)

if not os.path.exists(directorio):
    os.mkdir(directorio)

nombre_fichero_config_canal = os.path.join( config.get_library_path() , "series.xml" )
if not os.path.exists(nombre_fichero_config_canal):
    nombre_fichero_config_canal = os.path.join( config.get_data_path() , "series.xml" )

try:

    if config.get_setting("updatelibrary")=="true":
        config_canal = open( nombre_fichero_config_canal , "r" )
        
        for serie in config_canal.readlines():
コード例 #32
0
ファイル: library.py プロジェクト: kampanita/pelisalacarta
def convert_xml_to_json():
    logger.info("pelisalacarta.platformcode.library convert_xml_to_json")

    ruta_seriesold = os.path.join(config.get_library_path(), "SERIES_OLD")

    # Si ocurre un error durante la conversion y se crean las carpetas "SERIES"
    # y "SERIES_OLD", al reiniciar kodi os.rename dara un error, probablemente
    # sera "OSError: (66, 'Directory not empty')"
    if path_exists(ruta_seriesold):
        platformtools.dialog_notification("Actualizar biblioteca",
                                          "Actualizando desde XML")
        import shutil
        shutil.rmtree(ruta_seriesold)
        if not path_exists(ruta_seriesold):
            logger.info("pelisalacarta.platformcode.library eliminado: " + ruta_seriesold)
        else:
            logger.info("ERROR. No se ha podido eliminar: " + ruta_seriesold)
            platformtools.dialog_notification("ERROR",
                                              "No se actualizara la biblioteca")
            return False

    else:
        platformtools.dialog_ok("Biblioteca: Se va a actualizar al nuevo formato",
                                "Seleccione el nombre correcto de cada serie, si no está seguro pulse 'Cancelar'.",
                                "Hay nuevas opciones en 'Biblioteca' y en la 'configuración' del addon.")

    # TODO soporte samba
    os.rename(TVSHOWS_PATH, os.path.join(config.get_library_path(), "SERIES_OLD"))
    if not path_exists(TVSHOWS_PATH):

        make_dir(TVSHOWS_PATH)
        if path_exists(TVSHOWS_PATH):
            fname = join_path(config.get_data_path(), TVSHOW_FILE_OLD)
            dict_data = {}

            # TODO compatible con samba
            if path_exists(fname):
                try:
                    with open(fname, "r") as f:
                        for line in f:
                            aux = line.rstrip('\n').split(",")
                            tvshow = aux[0].strip()
                            url = aux[1].strip()
                            channel = aux[2].strip()

                            serie = Item()
                            serie.infoLabels = {}

                            patron = "^(.+)[\s]\((\d{4})\)$"
                            matches = re.compile(patron, re.DOTALL).findall(tvshow)

                            if matches:
                                serie.infoLabels['title'] = matches[0][0]
                                serie.infoLabels['year'] = matches[0][1]
                            else:
                                serie.infoLabels['title'] = tvshow

                            create_nfo = False

                            # Abrir ventana de seleccion para identificar la serie
                            serie = get_video_id_from_scraper(serie, True)

                            if 'id_Tmdb' in serie.infoLabels:
                                tvshow_id = serie.infoLabels['id_Tmdb']
                                create_nfo = True
                            else:
                                tvshow_id = "t_{0}_[{1}]".format(tvshow.strip().replace(" ", "_"), channel)

                            path = join_path(TVSHOWS_PATH, title_to_filename("{0} [{1}]".format(
                                tvshow.strip().lower(), channel)))

                            logger.info("pelisalacarta.platformcode.library savelibrary Creando directorio serie:" + path)
                            try:
                                make_dir(path)
                                if create_nfo:
                                    create_nfo_file(tvshow_id, path, "serie")

                            except OSError as exception:
                                if exception.errno != errno.EEXIST:
                                    raise

                            # Si la serie no existe en el registro ...
                            if tvshow_id not in dict_data:
                                # ... añadir la serie al registro
                                dict_data[tvshow_id] = {"name": serie.infoLabels['title'], "channels": {}}

                            # Si no hay datos del canal en el registro para esta serie...
                            if channel not in dict_data[tvshow_id]["channels"]:
                                # ... añadir canal al registro de la serie
                                dict_channel = {"tvshow": tvshow.strip(), "url": url, "path": path}
                                dict_data[tvshow_id]["channels"][channel] = dict_channel

                except EnvironmentError:
                    logger.info("ERROR al leer el archivo: {0}".format(fname))
                else:
                    # todo soporte samba
                    os.rename(join_path(config.get_data_path(), TVSHOW_FILE_OLD),
                              join_path(config.get_data_path(), "series_old.xml"))

                    json_data = jsontools.dump_json(dict_data)
                    save_file(json_data, join_path(config.get_data_path(), TVSHOW_FILE))

        else:
            logger.info("ERROR, no se ha podido crear la nueva carpeta de SERIES")
    else:
        logger.info("ERROR, no se ha podido renombrar la antigua carpeta de SERIES")

    # Por ultimo limpia la libreria, por que las rutas anteriores ya no existen
    xbmc.executebuiltin("CleanLibrary(video)")
コード例 #33
0
def get_next_items( item ):

    plugintools.log("navigation.get_next_items item="+item.tostring())

    try:
        # ----------------------------------------------------------------
        #  Main menu
        # ----------------------------------------------------------------
        if item.channel=="navigation":
		            # --- Update channels list ---------------------------------------
            from core import config
            if item.action=="mainlist":
                plugintools.log("navigation.get_next_items Main menu")

                if config.get_setting("updatechannels")=="true":
                    try:
                        from core import updater
                        actualizado = updater.updatechannel("channelselector")

                        if actualizado:
                            import xbmcgui
                            advertencia = xbmcgui.Dialog()
                            advertencia.ok("tvalacarta",config.get_localized_string(30064))
                    except:
                        pass
            # ----------------------------------------------------------------

            if item.action=="mainlist":
                plugintools.log("navigation.get_next_items Main menu")
                itemlist = channelselector.getmainlist("bannermenu")

        elif item.channel=="channelselector":

            if item.action=="channeltypes":
                plugintools.log("navigation.get_next_items Channel types menu")
                itemlist = channelselector.getchanneltypes("bannermenu")

            elif item.action=="listchannels":
                plugintools.log("navigation.get_next_items Channel list menu")
                itemlist = channelselector.filterchannels(item.category,"bannermenu")

        elif item.channel=="configuracion":
            plugintools.open_settings_dialog()
            return []

        else:

            if item.action=="":
                item.action="mainlist"

            plugintools.log("navigation.get_next_items Channel code ("+item.channel+"."+item.action+")")

            # --- Update channels files --------------------------------------
            if item.action=="mainlist":
                from core import config
                if config.get_setting("updatechannels")=="true":
                    try:
                        from core import updater
                        actualizado = updater.updatechannel(item.channel)

                        if actualizado:
                            import xbmcgui
                            advertencia = xbmcgui.Dialog()
                            advertencia.ok("plugin",item.channel,config.get_localized_string(30063))
                    except:
                        pass
            # ----------------------------------------------------------------

            try:
                exec "import channels."+item.channel+" as channel"
            except:
                exec "import core."+item.channel+" as channel"

            from platformcode import xbmctools

            if item.action=="play":
                plugintools.log("navigation.get_next_items play")

                # Si el canal tiene una acción "play" tiene prioridad
                if hasattr(channel, 'play'):
                    plugintools.log("streamondemand-pureita.navigation.py Channel has its own 'play' method")
                    itemlist = channel.play(item)
                    if len(itemlist)>0:
                        item = itemlist[0]

                        # FIXME: Este error ha que tratarlo de otra manera, al dar a volver sin ver el vídeo falla
                        try:
                            xbmctools.play_video(channel=item.channel, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=item.fulltitle, Serie=item.show)
                        except:
                            pass

                    else:
                        import xbmcgui
                        ventana_error = xbmcgui.Dialog()
                        ok = ventana_error.ok ("plugin", "No hay nada para reproducir")
                else:
                    plugintools.log("streamondemand-pureita.navigation.py No channel 'play' method, executing core method")

                    # FIXME: Este error ha que tratarlo de otra manera, por al dar a volver sin ver el vídeo falla
                    # Mejor hacer el play desde la ventana
                    try:
                        xbmctools.play_video(channel=item.channel, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=item.fulltitle, Serie=item.show)
                    except:
                        pass


                return []

            elif item.action=="findvideos":
                plugintools.log("navigation.get_next_items findvideos")

                # Si el canal tiene una acción "findvideos" tiene prioridad
                if hasattr(channel, 'findvideos'):
                    plugintools.log("streamondemand-pureita.navigation.py Channel has its own 'findvideos' method")
                    itemlist = channel.findvideos(item)
                else:
                    itemlist = []

                if len(itemlist)==0:
                    from servers import servertools
                    itemlist = servertools.find_video_items(item)

                if len(itemlist)==0:
                    itemlist = [ Item(title="No se han encontrado vídeos", thumbnail=os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_error.png" )) ]
            # ---------------add_serie_to_library-----------
            elif item.action=="add_serie_to_library":
                plugintools.log("navigation.get_next_items add_serie_to_library")
                from platformcode import library
                import xbmcgui
                
                # Obtiene el listado desde el que se llamó
                action = item.extra
                    
                # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
                if "###" in item.extra:
                    action = item.extra.split("###")[0]
                    item.extra = item.extra.split("###")[1]

                exec "itemlist = channel."+action+"(item)"

                # Progreso
                pDialog = xbmcgui.DialogProgress()
                ret = pDialog.create('streamondemand-pureita', 'Añadiendo episodios...')
                pDialog.update(0, 'Añadiendo episodio...')
                totalepisodes = len(itemlist)
                plugintools.log ("navigation.get_next_items Total Episodios:"+str(totalepisodes))
                i = 0
                errores = 0
                nuevos = 0
                for item in itemlist:
                    i = i + 1
                    pDialog.update(i*100/totalepisodes, 'Añadiendo episodio...',item.title)
                    plugintools.log("streamondemand-pureita.navigation.py add_serie_to_library, title="+item.title)
                    if (pDialog.iscanceled()):
                        return
                
                    try:
                        #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
                        # Añade todos menos el que dice "Añadir esta serie..." o "Descargar esta serie..."
                        if item.action!="add_serie_to_library" and item.action!="download_all_episodes":
                            nuevos = nuevos + library.savelibrary( titulo=item.title , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Series" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle, extra=item.extra )
                    except IOError:
                        import sys
                        for line in sys.exc_info():
                            logger.error( "%s" % line )
                        plugintools.log("streamondemand-pureita.navigation.py Error al grabar el archivo "+item.title)
                        errores = errores + 1
                        
                pDialog.close()
                    
                # Actualizacion de la biblioteca
                itemlist=[]
                if errores > 0:
                    itemlist.append(Item(title="ERRORE, la serie NON si è aggiunta alla biblioteca o la fatto in modo incompleto"))
                    plugintools.log ("navigation.get_next_items No se pudo añadir "+str(errores)+" episodios")
                else:
                    itemlist.append(Item(title="La serie è stata aggiunta alla biblioteca"))
                    plugintools.log ("navigation.get_next_items Ningún error al añadir "+str(errores)+" episodios")
                    
                # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
                #library.update(totalepisodes,errores,nuevos)
                #xbmctools.renderItems(itemlist, params, url, category)
                    
                #Lista con series para actualizar
                from core import config
                nombre_fichero_config_canal = os.path.join( config.get_library_path() , "series.xml" )
                if not os.path.exists(nombre_fichero_config_canal):
                    nombre_fichero_config_canal = os.path.join( config.get_data_path() , "series.xml" )

                plugintools.log("nombre_fichero_config_canal="+nombre_fichero_config_canal)
                if not os.path.exists(nombre_fichero_config_canal):
                    f = open( nombre_fichero_config_canal , "w" )
                else:
                    f = open( nombre_fichero_config_canal , "r" )
                    contenido = f.read()
                    f.close()
                    f = open( nombre_fichero_config_canal , "w" )
                    f.write(contenido)
                from platformcode import library
                f.write( library.title_to_folder_name(item.show)+","+item.url+","+item.channel+"\n")
                f.close();
                return itemlist
            # --------------------------------------------------------------------
            elif item.action=="download_all_episodes":
                plugintools.log("navigation.get_next_items download_all_episodes")
                download_all_episodes(item,channel)
			#---------------------------------------------------------------------
            else:

                if item.action=="search":
                    tecleado = plugintools.keyboard_input()
                    if tecleado!="":
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item,tecleado)
                elif item.channel=="novedades" and item.action=="mainlist":
                    itemlist = channel.mainlist(item,"bannermenu")
                elif item.channel=="buscador" and item.action=="mainlist":
                    itemlist = channel.mainlist(item,"bannermenu")
                else:
                    exec "itemlist = channel."+item.action+"(item)"

                for loaded_item in itemlist:

                    if loaded_item.thumbnail=="":
                        if loaded_item.folder:
                            loaded_item.thumbnail = os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_folder.png" )
                        else:
                            loaded_item.thumbnail = os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_nofolder.png" )

                if len(itemlist)==0:
                    itemlist = [ Item(title="No hay elementos para mostrar", thumbnail=os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_error.png" )) ]

    except:
        import traceback
        plugintools.log("navigation.get_next_items "+traceback.format_exc())
        itemlist = [ Item(title="Se ha producido un error", thumbnail=os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_error.png" )) ]


    return itemlist
コード例 #34
0
def add_serie_to_library(item):
    logger.info(
        "pelisalacarta.platformcode.launcher add_serie_to_library, show=#" +
        item.show + "#")
    from platformcode import library

    # Obtiene el listado desde el que se llamó
    action = item.extra

    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
    if "###" in item.extra:
        action = item.extra.split("###")[0]
        item.extra = item.extra.split("###")[1]

    exec "itemlist = channel." + action + "(item)"

    # Progreso
    pDialog = xplatformtools.dialog_progress('pelisalacarta',
                                             'Añadiendo episodios...')
    pDialog.update(0, 'Añadiendo episodio...')
    totalepisodes = len(itemlist)
    logger.info("[launcher.py] Total Episodios:" + str(totalepisodes))
    i = 0
    errores = 0
    nuevos = 0
    for item in itemlist:
        i = i + 1
        pDialog.update(i * 100 / totalepisodes, 'Añadiendo episodio...',
                       item.title)
        logger.info(
            "pelisalacarta.platformcode.launcher add_serie_to_library, title="
            + item.title)
        if (pDialog.iscanceled()):
            return

        try:
            #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
            # Añade todos menos el que dice "Añadir esta serie..." o "Descargar esta serie..."
            if item.action != "add_serie_to_library" and item.action != "download_all_episodes":
                nuevos = nuevos + library.savelibrary(
                    titulo=item.title,
                    url=item.url,
                    thumbnail=item.thumbnail,
                    server=item.server,
                    plot=item.plot,
                    canal=item.channel,
                    category="Series",
                    Serie=item.show.strip(),
                    verbose=False,
                    accion="play_from_library",
                    pedirnombre=False,
                    subtitle=item.subtitle,
                    extra=item.extra)
        except IOError:
            import sys
            for line in sys.exc_info():
                logger.error("%s" % line)
            logger.info(
                "pelisalacarta.platformcode.launcherError al grabar el archivo "
                + item.title)
            errores = errores + 1

    pDialog.close()

    # Actualizacion de la biblioteca
    itemlist = []
    if errores > 0:
        itemlist.append(
            Item(
                title=
                "ERROR, la serie NO se ha añadido a la biblioteca o lo ha hecho incompleta"
            ))
        logger.info("[launcher.py] No se pudo añadir " + str(errores) +
                    " episodios")
    else:
        itemlist.append(Item(title="La serie se ha añadido a la biblioteca"))
        logger.info("[launcher.py] Ningún error al añadir " + str(errores) +
                    " episodios")

    # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
    #library.update(totalepisodes,errores,nuevos)
    xbmctools.renderItems(itemlist, params, url, category)

    #Lista con series para actualizar
    nombre_fichero_config_canal = os.path.join(config.get_library_path(),
                                               "series.xml")
    if not os.path.exists(nombre_fichero_config_canal):
        nombre_fichero_config_canal = os.path.join(config.get_data_path(),
                                                   "series.xml")

    logger.info("nombre_fichero_config_canal=" + nombre_fichero_config_canal)
    if not os.path.exists(nombre_fichero_config_canal):
        f = open(nombre_fichero_config_canal, "w")
    else:
        f = open(nombre_fichero_config_canal, "r")
        contenido = f.read()
        f.close()
        f = open(nombre_fichero_config_canal, "w")
        f.write(contenido)
    from platformcode import library
    f.write(
        library.title_to_folder_name(item.show) + "," + item.url + "," +
        item.channel + "\n")
    f.close()
コード例 #35
0
def add_serie_to_library(item):
    logger.info("pelisalacarta.platformcode.launcher add_serie_to_library, show=#"+item.show+"#")
    from platformcode import library
    

    # Obtiene el listado desde el que se llamó
    action = item.extra
    
    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
    if "###" in item.extra:
        action = item.extra.split("###")[0]
        item.extra = item.extra.split("###")[1]

    exec "itemlist = channel."+action+"(item)"

    # Progreso
    pDialog = xplatformtools.dialog_progress('pelisalacarta', 'Añadiendo episodios...')
    pDialog.update(0, 'Añadiendo episodio...')
    totalepisodes = len(itemlist)
    logger.info ("[launcher.py] Total Episodios:"+str(totalepisodes))
    i = 0
    errores = 0
    nuevos = 0
    for item in itemlist:
        i = i + 1
        pDialog.update(i*100/totalepisodes, 'Añadiendo episodio...',item.title)
        logger.info("pelisalacarta.platformcode.launcher add_serie_to_library, title="+item.title)
        if (pDialog.iscanceled()):
            return

        try:
            #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
            # Añade todos menos el que dice "Añadir esta serie..." o "Descargar esta serie..."
            if item.action!="add_serie_to_library" and item.action!="download_all_episodes":
                nuevos = nuevos + library.savelibrary( titulo=item.title , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Series" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle, extra=item.extra )
        except IOError:
            import sys
            for line in sys.exc_info():
                logger.error( "%s" % line )
            logger.info("pelisalacarta.platformcode.launcherError al grabar el archivo "+item.title)
            errores = errores + 1
        
    pDialog.close()
    
    # Actualizacion de la biblioteca
    itemlist=[]
    if errores > 0:
        itemlist.append(Item(title="ERROR, la serie NO se ha añadido a la biblioteca o lo ha hecho incompleta"))
        logger.info ("[launcher.py] No se pudo añadir "+str(errores)+" episodios")
    else:
        itemlist.append(Item(title="La serie se ha añadido a la biblioteca"))
        logger.info ("[launcher.py] Ningún error al añadir "+str(errores)+" episodios")
    
    # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
    #library.update(totalepisodes,errores,nuevos)
    xbmctools.renderItems(itemlist, params, url, category)
    
    #Lista con series para actualizar
    nombre_fichero_config_canal = os.path.join( config.get_library_path() , "series.xml" )
    if not os.path.exists(nombre_fichero_config_canal):
        nombre_fichero_config_canal = os.path.join( config.get_data_path() , "series.xml" )

    logger.info("nombre_fichero_config_canal="+nombre_fichero_config_canal)
    if not os.path.exists(nombre_fichero_config_canal):
        f = open( nombre_fichero_config_canal , "w" )
    else:
        f = open( nombre_fichero_config_canal , "r" )
        contenido = f.read()
        f.close()
        f = open( nombre_fichero_config_canal , "w" )
        f.write(contenido)
    from platformcode import library
    f.write( library.title_to_folder_name(item.show)+","+item.url+","+item.channel+"\n")
    f.close();
コード例 #36
0
def findvideos_enlaces(item):
    logger.info("pelisalacarta.torrentlocurat findvideos")
    itemlist = []
    check_epi2=""
    data = httptools.downloadpage(item.url).data
    
    url= scrapertools.find_single_match(data,'window.location.href = "([^"]+)"').strip()
        
    try:
     
     if not url.endswith(".torrent") :
         url= httptools.downloadpage(url,follow_redirects=False)
         url=url.headers.get("location")
         
         if not url.endswith(".torrent") :
            url= httptools.downloadpage(url,follow_redirects=False)
            url=url.headers.get("location")
     else:
         url= httptools.downloadpage(url,follow_redirects=False)
         url=url.headers.get("location") 	
     torrents_path = config.get_library_path()+'/torrents'
            
     if not os.path.exists(torrents_path):
        os.mkdir(torrents_path)
     try:
        urllib.URLopener.version = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0' 
        urllib.urlretrieve (url, torrents_path+"/temp.torrent")
        pepe = open( torrents_path+"/temp.torrent", "rb").read()
     except:
        pepe = ""
     if "used CloudFlare" in pepe:
        try:
            urllib.urlretrieve("http://anonymouse.org/cgi-bin/anon-www.cgi/"+url.strip(), torrents_path+"/temp.torrent")
            pepe = open( torrents_path+"/temp.torrent", "rb").read()
        except:
            pepe=""
     torrent = decode(pepe)

     try:
        name = torrent["info"]["name"]
        sizet = torrent["info"]['length']
        sizet=convert_size(sizet)
     except:
        name = "no disponible"
     try:
        check_video = scrapertools.find_multiple_matches(str(torrent["info"]["files"]),"'length': (\d+)}")
                
        size=max([int(i) for i in check_video])
            
        for file in torrent["info"]["files"]:
            manolo = "%r - %d bytes" % ("/".join(file["path"]), file["length"])
            if str(size) in manolo:
                video= manolo
        size =convert_size(size)
        ext_v= re.sub(r"-.*? bytes|.*?\[.*?\].|'|.*?COM.|.*?\[.*?\]|\(.*?\)|.*?\.","",video)
        try:
         os.remove(torrents_path+"/temp.torrent")
        except:
            pass
     except:
        size = sizet
        ext_v= re.sub(r"-.*? bytes|.*?\[.*?\].|'|.*?COM.|.*?\.es.|.*?\[.*?\]|.*?\(.*?\)\.|.*?\.","",name)
        try:
            os.remove(torrents_path+"/temp.torrent")
        except:
            pass
    except:
        size = "en estos momentos..."
        ext_v= "no disponible"
    if "rar" in ext_v:
        ext_v= ext_v +" -- No reproducible"
    if item.contentType!="movie":
          fanart=item.extra.split("|")[1]
    else:
        fanart=item.extra.split("|")[0]
    itemlist.append( Item(channel=item.channel, title = "[COLOR orangered][B]Torrent[/B][/COLOR] "+"[COLOR lemonchiffon]( Video [/COLOR]"+"[COLOR lemonchiffon]"+ext_v+"--"+size+" )[/COLOR]" , url=url,  action="play",server="torrent", thumbnail=item.extra.split("|")[4], fanart=fanart, folder=False) )

    if item.contentType!="movie" :
       if "Capitulos" in item.extra.split("|")[9]:
          epis= scrapertools.find_multiple_matches(item.extra.split("|")[9],'Capitulos (\d+) al (\d+)')
          for epi1, epi2 in epis:
              len_epis= int(epi2)-int(epi1)
              if len_epis==1:
                 extra = item.extra+"|"+epi1
                 check_epi2="ok"
                 title_info ="    Info Cap."+epi1
                 title_info = "[COLOR indianred]"+title_info+"[/COLOR]"
                 itemlist.append( Item(channel=item.channel, action="info_capitulos" , title=title_info , url=item.url, thumbnail=item.extra.split("|")[6], fanart=item.extra.split("|")[1], extra=extra, folder=False ))
              else:
                  check_epi2=""
                  epis_len=range(int(epi1),int(epi2)+1)
                  extra = item.extra+"|"+str(epis_len)
                  title_info ="    Info Capítulos"
                  title_info = "[COLOR indianred]"+title_info+"[/COLOR]"
                  itemlist.append( Item(channel=item.channel, action="capitulos" , title=title_info , url=item.url, thumbnail=item.extra.split("|")[6], fanart=item.extra.split("|")[1], extra =extra, folder=True ))
       else:
          title_info ="    Info"
          title_info = "[COLOR indianred]"+title_info+"[/COLOR]"
          itemlist.append( Item(channel=item.channel, action="info_capitulos" , title=title_info , url=item.url, thumbnail=item.extra.split("|")[6], fanart=item.extra.split("|")[1], extra=item.extra, folder=False ))
       if check_epi2=="ok":
          extra = item.extra+"|"+epi2
          title_info ="    Info Cap."+epi2
          title_info = "[COLOR indianred]"+title_info+"[/COLOR]"
          itemlist.append( Item(channel=item.channel, action="info_capitulos" , title=title_info , url=item.url, thumbnail=item.extra.split("|")[6], fanart=item.extra.split("|")[1], extra=extra, folder=False ))
    dd=scrapertools.find_single_match(data,'DESCARGAS DIRECTA(.*?)VER ONLINE')
    if dd:
       extra = item.extra+"|"+ dd
       itemlist.append( Item(channel=item.channel, title = "[COLOR floralwhite][B]Descarga directa y online[/B][/COLOR]"  , url=item.url,  action="dd_y_o", thumbnail="http://imgur.com/as7Ie6p.png", fanart=item.extra.split("|")[1],contentType=item.contentType, extra=extra, folder=True) )
    return itemlist
コード例 #37
0
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import os
import sys

from core import config
from core import logger
from core.item import Item
from core import library
from core import guitools

directorio = os.path.join(config.get_library_path(),"SERIES")
if not os.path.exists(directorio):
    os.mkdir(directorio)
seriesxml = os.path.join( config.get_data_path() , "series.xml" )

if os.path.exists(seriesxml):
  if config.get_setting("updatelibrary")=="true":
      logger.info("Actualizando series...")
      
      f = open(seriesxml, "r")
      
      for serie in f.readlines():
          item = Item()
          item.deserialize(serie)
          carpeta=library.LimpiarNombre(item.show)
          ruta = os.path.join( config.get_library_path() , "SERIES" , carpeta )
          
コード例 #38
0
ファイル: playmax.py プロジェクト: d3v3l0p1n/mitvspain
def episodios(item):
    logger.info()
    itemlist = []

    # Descarga la página
    data = httptools.downloadpage(item.url).data
    data = re.sub(r"\n|\r|\t|\s{2}|&nbsp;|<br>", "", data)

    if not item.infoLabels["tmdb_id"]:
        item.infoLabels["tmdb_id"] = scrapertools.find_single_match(
            data, '<a href="https://www.themoviedb.org/[^/]+/(\d+)')
        item.infoLabels["year"] = scrapertools.find_single_match(
            data, 'class="e_new">(\d{4})')
    if not item.infoLabels["genre"]:
        item.infoLabels["genre"] = ", ".join(
            scrapertools.find_multiple_matches(
                data, '<a itemprop="genre"[^>]+>([^<]+)</a>'))
    if not item.infoLabels["plot"]:
        item.infoLabels["plot"] = scrapertools.find_single_match(
            data, 'itemprop="description">([^<]+)</div>')

    dc = scrapertools.find_single_match(data, "var dc_ic = '\?dc=([^']+)'")
    patron = '<div class="f_cl_l_c f_cl_l_c_id[^"]+" c_id="([^"]+)" .*?c_num="([^"]+)" c_name="([^"]+)"' \
             '.*?load_f_links\(\d+\s*,\s*(\d+).*?<div class="([^"]+)" onclick="marcar_capitulo'
    matches = scrapertools.find_multiple_matches(data, patron)
    lista_epis = []
    for c_id, episodio, title, ficha, status in matches:
        episodio = episodio.replace("X", "x")
        if episodio in lista_epis:
            continue
        lista_epis.append(episodio)
        url = "https://playmax.mx/c_enlaces_n.php?ficha=%s&c_id=%s&dc=%s" % (
            ficha, c_id, dc)
        title = "%s - %s" % (episodio, title)
        if "_mc a" in status:
            title = "[COLOR %s]%s[/COLOR] %s" % (
                color5, u"\u0474".encode('utf-8'), title)

        new_item = Item(channel=item.channel,
                        action="findvideos",
                        title=title,
                        url=url,
                        thumbnail=item.thumbnail,
                        fanart=item.fanart,
                        show=item.show,
                        infoLabels=item.infoLabels,
                        text_color=color2,
                        referer=item.url,
                        contentType="episode")
        try:
            new_item.infoLabels["season"], new_item.infoLabels[
                "episode"] = episodio.split('x', 1)
        except:
            pass
        itemlist.append(new_item)

    itemlist.sort(key=lambda it:
                  (it.infoLabels["season"], it.infoLabels["episode"]),
                  reverse=True)
    if __modo_grafico__:
        tmdb.set_infoLabels_itemlist(itemlist, __modo_grafico__)

    library_path = config.get_library_path()
    if config.get_library_support() and not item.extra:
        title = "Añadir serie a la biblioteca"
        if item.infoLabels["imdb_id"] and not library_path.lower().startswith(
                "smb://"):
            try:
                from core import filetools
                path = filetools.join(library_path, "SERIES")
                files = filetools.walk(path)
                for dirpath, dirname, filename in files:
                    if item.infoLabels["imdb_id"] in dirpath:
                        for f in filename:
                            if f != "tvshow.nfo":
                                continue
                            from core import library
                            head_nfo, it = library.read_nfo(
                                filetools.join(dirpath, dirname, f))
                            canales = it.library_urls.keys()
                            canales.sort()
                            if "playmax" in canales:
                                canales.pop(canales.index("playmax"))
                                canales.insert(0, "[COLOR red]playmax[/COLOR]")
                            title = "Serie ya en tu biblioteca. [%s] ¿Añadir?" % ",".join(
                                canales)
                            break
            except:
                import traceback
                logger.error(traceback.format_exc())
                pass

        itemlist.append(
            item.clone(action="add_serie_to_library",
                       title=title,
                       text_color=color5,
                       extra="episodios###library"))
    if itemlist and not __menu_info__:
        ficha = scrapertools.find_single_match(item.url, '-f(\d+)-')
        itemlist.extend(acciones_fichas(item, sid, ficha))

    return itemlist
コード例 #39
0
def main():
    logger.info("pelisalacarta.library_service Actualizando series...")

    directorio = library.join_path(config.get_library_path(), "SERIES")
    logger.info("directorio="+directorio)

    if not library.path_exists(directorio):
        library.make_dir(directorio)

    library.check_tvshow_xml()

    try:

        if config.get_setting("updatelibrary") == "true":

            data, dict_data = lib_data()

            heading = 'Actualizando biblioteca....'
            p_dialog = platformtools.dialog_progress_bg('pelisalacarta', heading)
            p_dialog.update(0, '')
            i = 0
            # fix float porque la division se hace mal en python 2.x
            t = float(100) / len(dict_data.keys())

            for tvshow_id in dict_data.keys():
                logger.info("pelisalacarta.library_service serie="+dict_data[tvshow_id]["name"])

                for channel in dict_data[tvshow_id]["channels"].keys():
                    carpeta = "{0} [{1}]".format(library.title_to_filename(
                        dict_data[tvshow_id]["channels"][channel]["tvshow"].lower()), channel)
                    # carpeta = dict_serie[tvshow_id]["channels"][channel]["path"]
                    ruta = library.join_path(config.get_library_path(), "SERIES", carpeta)
                    logger.info("pelisalacarta.library_service ruta =#"+ruta+"#")

                    i += 1
                    if library.path_exists(ruta):
                        logger.info("pelisalacarta.library_service Actualizando "+carpeta)
                        logger.info("pelisalacarta.library_service url " +
                                    dict_data[tvshow_id]["channels"][channel]["url"])

                        p_dialog.update(int(math.ceil(i * t)), heading, dict_data[tvshow_id]["name"])

                        item = Item(url=dict_data[tvshow_id]["channels"][channel]["url"],
                                    show=dict_data[tvshow_id]["channels"][channel]["tvshow"], channel=channel)

                        try:
                            pathchannels = library.join_path(config.get_runtime_path(), 'channels', channel + '.py')
                            logger.info("pelisalacarta.library_service Cargando canal  " + pathchannels + " " + channel)
                            obj = imp.load_source(channel, pathchannels)
                            itemlist = obj.episodios(item)

                            try:
                                library.save_library_tvshow(item, itemlist)
                            except Exception as ex:
                                logger.info("pelisalacarta.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(dict_data[tvshow_id]["channels"][channel]["tvshow"]))
                            template = "An exception of type {0} occured. Arguments:\n{1!r}"
                            message = template.format(type(ex).__name__, ex.args)
                            logger.info(message)
                    else:
                        logger.info("pelisalacarta.library_service No actualiza {0} (no existe el directorio)".
                                    format(dict_data[tvshow_id]["name"]))

                        p_dialog.update(int(math.ceil(i * t)), 'Error al obtener ruta...', dict_data[tvshow_id]["name"])

            p_dialog.close()
            library.update()
        else:
            logger.info("No actualiza la biblioteca, está desactivado en la configuración de pelisalacarta")

    except Exception as ex:
        import traceback
        logger.info(traceback.format_exc())

        if p_dialog:
            p_dialog.close()
コード例 #40
0
        itemlist=[]
 
       



#############################################################
# Main                                                      #
#############################################################
logger.info("[library_service.py] Actualizando series...")
Inicio = time.time() 
lista_nuevos_capitulos = []

try:
    if config.get_setting("updatelibrary")=="true":
        SERIES_PATH = os.path.join(config.get_library_path(), 'SERIES')
        if not os.path.exists(SERIES_PATH): os.mkdir(SERIES_PATH)
        
        nombre_fichero_listado_series = os.path.join( config.get_library_path() , "series.xml" )
        if not os.path.exists(nombre_fichero_listado_series):
            nombre_fichero_listado_series = os.path.join( config.get_data_path() , "series.xml" )
            
        fichero_listado_series = open( nombre_fichero_listado_series , "r" )

        multihilo= (config.get_setting("multithread") !='false' ) #Por defecto esta activado
        listahilos=[]
        for serie in fichero_listado_series.readlines():
            if multihilo:
                from threading import Thread
                Trd = Thread(target=actualizarSerie,args=[serie])
                listahilos.append(Trd)
コード例 #41
0
import sys
import xbmc, time

from core import scrapertools
from core import config
from core import logger
from core.item import Item
from servers import servertools

logger.info("streamondemand-pureita.library_service Actualizando series...")
from platformcode import library
from platformcode import launcher
import xbmcgui
import imp

directorio = os.path.join(config.get_library_path(), "SERIES")
logger.info("directorio=" + directorio)

if not os.path.exists(directorio):
    os.mkdir(directorio)

nombre_fichero_config_canal = os.path.join(config.get_library_path(),
                                           "series.xml")
if not os.path.exists(nombre_fichero_config_canal):
    nombre_fichero_config_canal = os.path.join(config.get_data_path(),
                                               "series.xml")

try:

    if config.get_setting("updatelibrary") == "true":
        config_canal = open(nombre_fichero_config_canal, "r")
コード例 #42
0
def peliculas(item):
    logger.info("pelisalacarta.channels.biblioteca peliculas")
    strm_path = library.MOVIES_PATH
    download_path = filetools.join(config.get_library_path(), "Descargas",
                                   "Cine")

    itemlist = []

    for raiz, subcarpetas, ficheros in filetools.walk(strm_path):
        for f in ficheros:
            if f.endswith(".strm"):
                i = filetools.join(raiz, f)

                movie = Item().fromurl(filetools.read(i))
                movie.contentChannel = movie.channel
                movie.path = i
                movie.title = os.path.splitext(
                    os.path.basename(i))[0].capitalize()
                movie.channel = "biblioteca"
                movie.action = "findvideos"
                movie.text_color = "blue"
                # fix para que no se ejecute el método de play para la biblioteca de Kodi
                movie.strm = False

                itemlist.append(movie)

    # Obtenemos todos los videos de la biblioteca de CINE recursivamente
    for raiz, subcarpetas, ficheros in filetools.walk(download_path):
        for f in ficheros:
            if not f.endswith(".json") and not f.endswith(
                    ".nfo") and not f.endswith(".srt"):
                i = filetools.join(raiz, f)

                movie = Item()
                movie.contentChannel = "local"
                movie.path = i
                movie.title = os.path.splitext(
                    os.path.basename(i))[0].capitalize()
                movie.channel = "biblioteca"
                movie.action = "play"
                movie.text_color = "green"

                itemlist.append(movie)

    library.set_infolabels_from_library(itemlist, tipo='Movies')

    # Agrupamos las peliculas por canales
    join_itemlist = []

    for i in range(len(itemlist)):
        encontrado = False
        for j in range(i + 1, len(itemlist)):
            if "tmdb_id" in itemlist[i].infoLabels and "tmdb_id" in itemlist[
                    j].infoLabels:
                if itemlist[i].infoLabels["tmdb_id"] == itemlist[j].infoLabels[
                        "tmdb_id"]:
                    encontrado = True

                    if "list_channels" not in itemlist[i]:
                        list_channels = []
                        dict_first_channel = {
                            "path": itemlist[i].path,
                            "channel": itemlist[i].contentChannel
                        }
                        list_channels.append(dict_first_channel.copy())
                        itemlist[j].list_channels = list_channels

                    dict_other_channel = {
                        "path": itemlist[j].path,
                        "channel": itemlist[j].contentChannel
                    }
                    itemlist[j].list_channels.append(dict_other_channel.copy())
                    itemlist[j].action = "get_canales_movies"
                    itemlist[j].text_color = "orange"

        # TODO pendiente de probar
        if "contentTitle" in itemlist[i] and itemlist[i].contentTitle != "":
            itemlist[i].title = itemlist[i].contentTitle

        if not encontrado:
            join_itemlist.append(itemlist[i])

    return sorted(join_itemlist, key=lambda it: it.title.lower())
コード例 #43
0
def series(item):
    logger.info("pelisalacarta.channels.biblioteca series")
    strm_path = library.TVSHOWS_PATH
    download_path = filetools.join(config.get_library_path(), "Descargas", "Series")

    itemlist = []

    # Obtenemos todos los strm de la biblioteca de SERIES recursivamente
    for raiz, subcarpetas, ficheros in filetools.walk(strm_path):
        for f in ficheros:
            if f == "tvshow.json":
                i = filetools.join(raiz, f)

                tvshow = Item().fromjson(filetools.read(i))
                logger.debug(tvshow.tostring())
                tvshow.contentChannel = tvshow.channel
                tvshow.path = os.path.dirname(i)
                tvshow.title = os.path.basename(os.path.dirname(i))
                tvshow.channel = "biblioteca"
                tvshow.action = "get_temporadas"
                tvshow.text_color = "blue"

                itemlist.append(tvshow)

    # Obtenemos todos los videos de la biblioteca de SERIES recursivamente
    for raiz, subcarpetas, ficheros in filetools.walk(download_path):
        for f in ficheros:
            if f == "tvshow.json":
                i = filetools.join(raiz, f)

                tvshow = Item().fromjson(filetools.read(i))
                tvshow.contentChannel = "local"
                tvshow.path = os.path.dirname(i)
                tvshow.title = os.path.basename(os.path.dirname(i))
                tvshow.channel = "biblioteca"
                tvshow.action = "get_temporadas"
                tvshow.text_color = "green"

                itemlist.append(tvshow)

    library.set_infolabels_from_library(itemlist, tipo="TVShows")

    # Agrupamos las series por canales
    join_itemlist = []

    for i in range(len(itemlist)):
        encontrado = False
        for j in range(i + 1, len(itemlist)):
            if "tmdb_id" in itemlist[i].infoLabels and "tmdb_id" in itemlist[j].infoLabels:
                if itemlist[i].infoLabels["tmdb_id"] == itemlist[j].infoLabels["tmdb_id"]:
                    encontrado = True

                    if "list_channels" not in itemlist[i]:
                        list_channels = []
                        dict_first_channel = {"path": itemlist[i].path, "channel": itemlist[i].contentChannel}
                        list_channels.append(dict_first_channel.copy())
                        itemlist[j].list_channels = list_channels

                    dict_other_channel = {"path": itemlist[j].path, "channel": itemlist[j].contentChannel}
                    itemlist[j].list_channels.append(dict_other_channel.copy())
                    itemlist[j].action = "get_canales_tvshow"
                    itemlist[j].text_color = "orange"

        if "contentTitle" in itemlist[i] and itemlist[i].contentTitle != "":
            itemlist[i].title = itemlist[i].contentTitle

        if not encontrado:
            join_itemlist.append(itemlist[i])

    return sorted(join_itemlist, key=lambda it: it.title.lower())
コード例 #44
0
def run():
    logger.info("streamondemand-pureita.platformcode.launcher run")

    # Test if all the required directories are created
    config.verify_directories_created()

    # Extract parameters from sys.argv
    params, fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, viewmode, category, show, password = (
        extract_parameters()
    )
    logger.info(
        "streamondemand-pureita.platformcode.launcher fanart=%s, channel_name=%s, title=%s, fulltitle=%s, url=%s, thumbnail=%s, plot=%s, action=%s, server=%s, extra=%s, subtitle=%s, category=%s, show=%s, password=%s"
        % (
            fanart,
            channel_name,
            title,
            fulltitle,
            url,
            thumbnail,
            plot,
            action,
            server,
            extra,
            subtitle,
            category,
            show,
            password,
        )
    )

    try:
        # Accion por defecto - elegir canal
        if action == "selectchannel":
            # Borra el fichero de las cookies para evitar problemas con MV
            # ficherocookies = os.path.join( config.get_data_path(), 'cookies.lwp' )
            # if os.path.exists(ficherocookies):
            #    os.remove(ficherocookies)

            """
            if config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel("channelselector")

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("tvalacarta",config.get_localized_string(30064))
                except:
                    pass
            """

            import channelselector as plugin

            plugin.mainlist(params, url, category)

        # Actualizar version
        elif action == "update":
            try:
                from core import updater

                updater.update(params)
            except ImportError:
                logger.info("streamondemand-pureita.platformcode.launcher Actualizacion automática desactivada")

            # import channelselector as plugin
            # plugin.listchannels(params, url, category)
            if config.get_system_platform() != "xbox":
                import xbmc

                xbmc.executebuiltin("Container.Refresh")

        elif action == "channeltypes":
            import channelselector as plugin

            plugin.channeltypes(params, url, category)

        elif action == "categories":
            import channelselector as plugin

            plugin.categories(params, url, category)

        elif action == "listchannels":
            import channelselector as plugin

            plugin.listchannels(params, url, category)

        # El resto de acciones vienen en el parámetro "action", y el canal en el parámetro "channel"
        else:
            """
            if action=="mainlist" and config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel(channel_name)

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("plugin",channel_name,config.get_localized_string(30063))
                except:
                    pass
            """

            # La acción puede estar en el core, o ser un canal regular. El buscador es un canal especial que está en streamondemand-pureita
            regular_channel_path = os.path.join(config.get_runtime_path(), "channels", channel_name + ".py")
            core_channel_path = os.path.join(config.get_runtime_path(), "core", channel_name + ".py")
            logger.info("streamondemand-pureita.platformcode.launcher regular_channel_path=%s" % regular_channel_path)
            logger.info("streamondemand-pureita.platformcode.launcher core_channel_path=%s" % core_channel_path)

            if (
                channel_name == "personal"
                or channel_name == "personal2"
                or channel_name == "personal3"
                or channel_name == "personal4"
                or channel_name == "personal5"
            ):
                import channels.personal as channel
            elif os.path.exists(regular_channel_path):
                exec "import channels." + channel_name + " as channel"
            elif os.path.exists(core_channel_path):
                exec "from core import " + channel_name + " as channel"

            logger.info(
                "streamondemand-pureita.platformcode.launcher running channel %s %s"
                % (channel.__name__, channel.__file__)
            )

            generico = False
            # Esto lo he puesto asi porque el buscador puede ser generico o normal, esto estará asi hasta que todos los canales sean genericos
            if category == "Buscador_Generico":
                generico = True
            else:
                try:
                    generico = channel.isGeneric()
                except:
                    generico = False

            if not generico:
                logger.info("streamondemand-pureita.platformcode.launcher xbmc native channel")
                if action == "strm":
                    from platformcode import xbmctools

                    xbmctools.playstrm(params, url, category)
                else:
                    exec "channel." + action + "(params, url, category)"
            else:
                logger.info("streamondemand-pureita.platformcode.launcher multiplatform channel")
                from core.item import Item

                item = Item(
                    channel=channel_name,
                    title=title,
                    fulltitle=fulltitle,
                    url=url,
                    thumbnail=thumbnail,
                    plot=plot,
                    server=server,
                    category=category,
                    extra=extra,
                    subtitle=subtitle,
                    viewmode=viewmode,
                    show=show,
                    password=password,
                    fanart=fanart,
                )

                """
                if item.subtitle!="":
                    logger.info("streamondemand-pureita.platformcode.launcher Downloading subtitle file "+item.subtitle)
                    from core import downloadtools
                    
                    ficherosubtitulo = os.path.join( config.get_data_path() , "subtitulo.srt" )
                    if os.path.exists(ficherosubtitulo):
                        os.remove(ficherosubtitulo)

                    downloadtools.downloadfile(item.subtitle, ficherosubtitulo )
                    config.set_setting("subtitulo","true")
                else:
                    logger.info("streamondemand-pureita.platformcode.launcher No subtitle")
                """
                from platformcode import xbmctools

                if action == "play":
                    logger.info("streamondemand-pureita.platformcode.launcher play")
                    # Si el canal tiene una acción "play" tiene prioridad
                    if hasattr(channel, "play"):
                        logger.info("streamondemand-pureita.platformcode.launcher executing channel 'play' method")
                        itemlist = channel.play(item)
                        if len(itemlist) > 0:
                            item = itemlist[0]
                            xbmctools.play_video(
                                channel=channel_name,
                                server=item.server,
                                url=item.url,
                                category=item.category,
                                title=item.title,
                                thumbnail=item.thumbnail,
                                plot=item.plot,
                                extra=item.extra,
                                subtitle=item.subtitle,
                                video_password=item.password,
                                fulltitle=item.fulltitle,
                                Serie=item.show,
                            )
                        else:
                            import xbmcgui

                            ventana_error = xbmcgui.Dialog()
                            ok = ventana_error.ok("plugin", "No hay nada para reproducir")
                    else:
                        logger.info(
                            "streamondemand-pureita.platformcode.launcher no channel 'play' method, executing core method"
                        )
                        xbmctools.play_video(
                            channel=channel_name,
                            server=item.server,
                            url=item.url,
                            category=item.category,
                            title=item.title,
                            thumbnail=item.thumbnail,
                            plot=item.plot,
                            extra=item.extra,
                            subtitle=item.subtitle,
                            video_password=item.password,
                            fulltitle=item.fulltitle,
                            Serie=item.show,
                        )

                elif action == "strm_detail" or action == "play_from_library":
                    logger.info("streamondemand-pureita.platformcode.launcher play_from_library")

                    fulltitle = item.show + " " + item.title
                    elegido = Item(url="")

                    logger.info("item.server=#" + item.server + "#")
                    # Ejecuta find_videos, del canal o común
                    try:
                        itemlist = channel.findvideos(item)
                    except:
                        from servers import servertools

                        itemlist = servertools.find_video_items(item)

                    if len(itemlist) > 0:
                        # for item2 in itemlist:
                        #    logger.info(item2.title+" "+item2.subtitle)

                        # El usuario elige el mirror
                        opciones = []
                        for item in itemlist:
                            opciones.append(item.title)

                        import xbmcgui

                        dia = xbmcgui.Dialog()
                        seleccion = dia.select(config.get_localized_string(30163), opciones)
                        elegido = itemlist[seleccion]

                        if seleccion == -1:
                            return
                    else:
                        elegido = item

                    # Ejecuta el método play del canal, si lo hay
                    try:
                        itemlist = channel.play(elegido)
                        item = itemlist[0]
                    except:
                        item = elegido
                    logger.info("Elegido %s (sub %s)" % (item.title, item.subtitle))

                    from platformcode import xbmctools

                    logger.info("subtitle=" + item.subtitle)
                    xbmctools.play_video(
                        strmfile=True,
                        channel=item.channel,
                        server=item.server,
                        url=item.url,
                        category=item.category,
                        title=item.title,
                        thumbnail=item.thumbnail,
                        plot=item.plot,
                        extra=item.extra,
                        subtitle=item.subtitle,
                        video_password=item.password,
                        fulltitle=fulltitle,
                    )

                elif action == "add_pelicula_to_library":
                    logger.info("streamondemand-pureita.platformcode.launcher add_pelicula_to_library")
                    from platformcode import library

                    # Obtiene el listado desde el que se llamó
                    library.savelibrary(
                        titulo=item.fulltitle,
                        url=item.url,
                        thumbnail=item.thumbnail,
                        server=item.server,
                        plot=item.plot,
                        canal=item.channel,
                        category="Cine",
                        Serie=item.show.strip(),
                        verbose=False,
                        accion="play_from_library",
                        pedirnombre=False,
                        subtitle=item.subtitle,
                    )

                elif action == "add_serie_to_library":
                    logger.info(
                        "streamondemand-pureita.platformcode.launcher add_serie_to_library, show=#" + item.show + "#"
                    )
                    from platformcode import library
                    import xbmcgui

                    # Obtiene el listado desde el que se llamó
                    action = item.extra

                    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
                    if "###" in item.extra:
                        action = item.extra.split("###")[0]
                        item.extra = item.extra.split("###")[1]

                    exec "itemlist = channel." + action + "(item)"

                    # Progreso
                    pDialog = xbmcgui.DialogProgress()
                    ret = pDialog.create("streamondemand-pureita", "Añadiendo episodios...")
                    pDialog.update(0, "Añadiendo episodio...")
                    totalepisodes = len(itemlist)
                    logger.info("[launcher.py] Total Episodios:" + str(totalepisodes))
                    i = 0
                    errores = 0
                    nuevos = 0
                    for item in itemlist:
                        i = i + 1
                        pDialog.update(i * 100 / totalepisodes, "Añadiendo episodio...", item.title)
                        logger.info(
                            "streamondemand-pureita.platformcode.launcher add_serie_to_library, title=" + item.title
                        )
                        if pDialog.iscanceled():
                            return

                        try:
                            # (titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
                            # Añade todos menos el que dice "Añadir esta serie..." o "Descargar esta serie..."
                            if item.action != "add_serie_to_library" and item.action != "download_all_episodes":
                                nuevos = nuevos + library.savelibrary(
                                    titulo=item.title,
                                    url=item.url,
                                    thumbnail=item.thumbnail,
                                    server=item.server,
                                    plot=item.plot,
                                    canal=item.channel,
                                    category="Series",
                                    Serie=item.show.strip(),
                                    verbose=False,
                                    accion="play_from_library",
                                    pedirnombre=False,
                                    subtitle=item.subtitle,
                                    extra=item.extra,
                                )
                        except IOError:
                            import sys

                            for line in sys.exc_info():
                                logger.error("%s" % line)
                            logger.info(
                                "streamondemand-pureita.platformcode.launcher Error al grabar el archivo " + item.title
                            )
                            errores = errores + 1

                    pDialog.close()

                    # Actualizacion de la biblioteca
                    itemlist = []
                    if errores > 0:
                        itemlist.append(
                            Item(
                                title="ERRORE, la serie NON si è aggiunta alla biblioteca o la fatto in modo incompleto"
                            )
                        )
                        logger.info("[launcher.py] No se pudo añadir " + str(errores) + " episodios")
                    else:
                        itemlist.append(Item(title="La serie è stata aggiunta alla biblioteca"))
                        logger.info("[launcher.py] Ningún error al añadir " + str(errores) + " episodios")

                    # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
                    # library.update(totalepisodes,errores,nuevos)
                    xbmctools.renderItems(itemlist, params, url, category)

                    # Lista con series para actualizar
                    nombre_fichero_config_canal = os.path.join(config.get_library_path(), "series.xml")
                    if not os.path.exists(nombre_fichero_config_canal):
                        nombre_fichero_config_canal = os.path.join(config.get_data_path(), "series.xml")

                    logger.info("nombre_fichero_config_canal=" + nombre_fichero_config_canal)
                    if not os.path.exists(nombre_fichero_config_canal):
                        f = open(nombre_fichero_config_canal, "w")
                    else:
                        f = open(nombre_fichero_config_canal, "r")
                        contenido = f.read()
                        f.close()
                        f = open(nombre_fichero_config_canal, "w")
                        f.write(contenido)
                    from platformcode import library

                    f.write(library.title_to_folder_name(item.show) + "," + item.url + "," + item.channel + "\n")
                    f.close()

                elif action == "download_all_episodes":
                    download_all_episodes(item, channel)

                elif action == "search":
                    logger.info("streamondemand-pureita.platformcode.launcher search")
                    import xbmc

                    keyboard = xbmc.Keyboard("")
                    keyboard.doModal()
                    if keyboard.isConfirmed():
                        tecleado = keyboard.getText()
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item, tecleado)
                    else:
                        itemlist = []
                    xbmctools.renderItems(itemlist, params, url, category)

                else:
                    logger.info(
                        "streamondemand-pureita.platformcode.launcher executing channel '" + action + "' method"
                    )
                    if action != "findvideos":
                        exec "itemlist = channel." + action + "(item)"

                        # for item in itemlist:
                        #    logger.info("viemode="+item.viewmode)
                    else:

                        # Intenta ejecutar una posible funcion "findvideos" del canal
                        if hasattr(channel, "findvideos"):
                            exec "itemlist = channel." + action + "(item)"
                        # Si no funciona, lanza el método genérico para detectar vídeos
                        else:
                            logger.info(
                                "streamondemand-pureita.platformcode.launcher no channel 'findvideos' method, executing core method"
                            )
                            from servers import servertools

                            itemlist = servertools.find_video_items(item)

                        from platformcode import subtitletools

                        subtitletools.saveSubtitleName(item)

                    # Activa el modo biblioteca para todos los canales genéricos, para que se vea el argumento
                    import xbmcplugin
                    import sys

                    handle = sys.argv[1]
                    xbmcplugin.setContent(int(handle), "movies")

                    # Añade los items a la lista de XBMC
                    xbmctools.renderItems(itemlist, params, url, category)

    except urllib2.URLError, e:
        import traceback, sys
        from pprint import pprint

        exc_type, exc_value, exc_tb = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_tb)
        for line in lines:
            line_splits = line.split("\n")
            for line_split in line_splits:
                logger.error(line_split)

        import xbmcgui

        ventana_error = xbmcgui.Dialog()
        # Agarra los errores surgidos localmente enviados por las librerias internas
        if hasattr(e, "reason"):
            logger.info("Razon del error, codigo: %d , Razon: %s" % (e.reason[0], e.reason[1]))
            texto = config.get_localized_string(30050)  # "No se puede conectar con el sitio web"
            ok = ventana_error.ok("plugin", texto)
        # Agarra los errores con codigo de respuesta del servidor externo solicitado
        elif hasattr(e, "code"):
            logger.info("codigo de error HTTP : %d" % e.code)
            texto = (
                config.get_localized_string(30051) % e.code
            )  # "El sitio web no funciona correctamente (error http %d)"
            ok = ventana_error.ok("plugin", texto)
コード例 #45
0
from core import config
from core import logger
from core import downloadtools
from core import scrapertools
from core.item import Item
import cliente


DEBUG = config.get_setting("debug")

__type__ = "generic"
__title__ = "Libreria"
__channel__ = "library"

logger.info("[library.py] init")
MOVIES_PATH = os.path.join(config.get_library_path(), 'CINE')
SERIES_PATH = os.path.join(config.get_library_path(), 'SERIES')
if not os.path.exists(config.get_library_path()): os.mkdir(config.get_library_path())
if not os.path.exists(MOVIES_PATH): os.mkdir(MOVIES_PATH)
if not os.path.exists(SERIES_PATH): os.mkdir(SERIES_PATH)

def isGeneric():
    return True

def LimpiarNombre(nombre):
  allchars = string.maketrans('', '')
  deletechars = '\\/:*"<>|?' #Caracteres no váidos en nombres de archivo
  return string.translate(nombre,allchars,deletechars)
    
     
def Guardar(item):
コード例 #46
0
from core import config
from core import logger
from core import downloadtools
from core import scrapertools
from core.item import Item
import xbmc
import xbmcgui

DEBUG = config.get_setting("debug")

__type__ = "generic"
__title__ = "Libreria"
__channel__ = "library"

logger.info("[library.py] init")
MOVIES_PATH = os.path.join(config.get_library_path(), 'CINE')
SERIES_PATH = os.path.join(config.get_library_path(), 'SERIES')

if not os.path.exists(config.get_library_path()):
    os.mkdir(config.get_library_path())
if not os.path.exists(MOVIES_PATH): os.mkdir(MOVIES_PATH)
if not os.path.exists(SERIES_PATH): os.mkdir(SERIES_PATH)


def isGeneric():
    return True


def LimpiarNombre(nombre):
    nombre = nombre.strip()
    allchars = string.maketrans('', '')
コード例 #47
0
def series(item):
    logger.info("pelisalacarta.channels.biblioteca series")
    strm_path = library.TVSHOWS_PATH
    download_path = filetools.join(config.get_library_path(), "Descargas",
                                   "Series")

    itemlist = []

    # Obtenemos todos los strm de la biblioteca de SERIES recursivamente
    for raiz, subcarpetas, ficheros in filetools.walk(strm_path):
        for f in ficheros:
            if f == "tvshow.json":
                i = filetools.join(raiz, f)

                tvshow = Item().fromjson(filetools.read(i))
                logger.debug(tvshow.tostring())
                tvshow.contentChannel = tvshow.channel
                tvshow.path = os.path.dirname(i)
                tvshow.title = os.path.basename(os.path.dirname(i))
                tvshow.channel = "biblioteca"
                tvshow.action = "get_temporadas"
                tvshow.text_color = "blue"

                itemlist.append(tvshow)

    # Obtenemos todos los videos de la biblioteca de SERIES recursivamente
    for raiz, subcarpetas, ficheros in filetools.walk(download_path):
        for f in ficheros:
            if f == "tvshow.json":
                i = filetools.join(raiz, f)

                tvshow = Item().fromjson(filetools.read(i))
                tvshow.contentChannel = "local"
                tvshow.path = os.path.dirname(i)
                tvshow.title = os.path.basename(os.path.dirname(i))
                tvshow.channel = "biblioteca"
                tvshow.action = "get_temporadas"
                tvshow.text_color = "green"

                itemlist.append(tvshow)

    library.set_infolabels_from_library(itemlist, tipo='TVShows')

    # Agrupamos las series por canales
    join_itemlist = []

    for i in range(len(itemlist)):
        encontrado = False
        for j in range(i + 1, len(itemlist)):
            if "tmdb_id" in itemlist[i].infoLabels and "tmdb_id" in itemlist[
                    j].infoLabels:
                if itemlist[i].infoLabels["tmdb_id"] == itemlist[j].infoLabels[
                        "tmdb_id"]:
                    encontrado = True

                    if "list_channels" not in itemlist[i]:
                        list_channels = []
                        dict_first_channel = {
                            "path": itemlist[i].path,
                            "channel": itemlist[i].contentChannel
                        }
                        list_channels.append(dict_first_channel.copy())
                        itemlist[j].list_channels = list_channels

                    dict_other_channel = {
                        "path": itemlist[j].path,
                        "channel": itemlist[j].contentChannel
                    }
                    itemlist[j].list_channels.append(dict_other_channel.copy())
                    itemlist[j].action = "get_canales_tvshow"
                    itemlist[j].text_color = "orange"

        if "contentTitle" in itemlist[i] and itemlist[i].contentTitle != "":
            itemlist[i].title = itemlist[i].contentTitle

        if not encontrado:
            join_itemlist.append(itemlist[i])

    return sorted(join_itemlist, key=lambda it: it.title.lower())
コード例 #48
0
import xbmc,time

from core import scrapertools
from core import config
from core import logger
from core.item import Item
from servers import servertools

logger.info("[library_service.py] Actualizando series...")
from platformcode.xbmc import library
from platformcode.xbmc import launcher
import xbmcgui

#Eliminar carpeta antes de actualizar
    
directorio = os.path.join(config.get_library_path(),"SERIES")
logger.info ("directorio="+directorio)
import shutil

#if os.path.exists(directorio):
#    shutil.rmtree(directorio)

if not os.path.exists(directorio):
    os.mkdir(directorio)

nombre_fichero_config_canal = os.path.join( config.get_data_path() , "series.xml" )

try:

    if config.get_setting("updatelibrary")=="true":
        config_canal = open( nombre_fichero_config_canal , "r" )
コード例 #49
0
from core import downloadtools
from core import scrapertools

CHANNELNAME = "library"
allchars = string.maketrans('', '')
deletechars = '\\/:*"<>|?' #Caracteres no válidos en nombres de archivo
# Esto permite su ejecución en modo emulado (preguntar a jesus por esto)
# seguro que viene bien para debuguear
try:
    pluginhandle = int( sys.argv[ 1 ] )
except:
    pluginhandle = ""

DEBUG = True

LIBRARY_PATH = config.get_library_path()
if not os.path.exists(LIBRARY_PATH):
    logger.info("[library.py] Library path doesn't exist:"+LIBRARY_PATH)
    config.verify_directories_created()

#MOVIES_PATH
MOVIES_PATH = xbmc.translatePath( os.path.join( LIBRARY_PATH, 'CINE' ) )
if not os.path.exists(MOVIES_PATH):
    logger.info("[library.py] Movies path doesn't exist:"+MOVIES_PATH)
    os.mkdir(MOVIES_PATH)

#SERIES_PATH
SERIES_PATH = xbmc.translatePath( os.path.join( LIBRARY_PATH, 'SERIES' ) )
if not os.path.exists(SERIES_PATH):
    logger.info("[library.py] Series path doesn't exist:"+SERIES_PATH)
    os.mkdir(SERIES_PATH)
コード例 #50
0
def run():
    logger.info("[launcher.py] run")

    # Test if all the required directories are created
    config.verify_directories_created()

    # Extract parameters from sys.argv
    params, fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, viewmode, category, show, password = extract_parameters(
    )
    logger.info(
        "[launcher.py] fanart=%s, channel_name=%s, title=%s, fulltitle=%s, url=%s, thumbnail=%s, plot=%s, action=%s, server=%s, extra=%s, subtitle=%s, category=%s, show=%s, password=%s"
        % (fanart, channel_name, title, fulltitle, url, thumbnail, plot,
           action, server, extra, subtitle, category, show, password))

    try:
        # Accion por defecto - elegir canal
        if (action == "selectchannel"):
            # Borra el fichero de las cookies para evitar problemas con MV
            #ficherocookies = os.path.join( config.get_data_path(), 'cookies.lwp' )
            #if os.path.exists(ficherocookies):
            #    os.remove(ficherocookies)

            if config.get_setting("updatechannels") == "true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel("channelselector")

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("tvalacarta",
                                       config.get_localized_string(30064))
                except:
                    pass

            import channelselector as plugin
            plugin.mainlist(params, url, category)

        # Actualizar version
        elif (action == "update"):
            try:
                from core import updater
                updater.update(params)
            except ImportError:
                logger.info(
                    "[launcher.py] Actualizacion automática desactivada")

            #import channelselector as plugin
            #plugin.listchannels(params, url, category)
            if config.get_system_platform() != "xbox":
                import xbmc
                xbmc.executebuiltin("Container.Refresh")

        elif (action == "channeltypes"):
            import channelselector as plugin
            plugin.channeltypes(params, url, category)

        elif (action == "listchannels"):
            import channelselector as plugin
            plugin.listchannels(params, url, category)

        # El resto de acciones vienen en el parámetro "action", y el canal en el parámetro "channel"
        else:
            if action == "mainlist" and config.get_setting(
                    "updatechannels") == "true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel(channel_name)

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("plugin", channel_name,
                                       config.get_localized_string(30063))
                except:
                    pass

            # La acción puede estar en el core, o ser un canal regular. El buscador es un canal especial que está en pelisalacarta
            regular_channel_path = os.path.join(config.get_runtime_path(),
                                                PLUGIN_NAME, 'channels',
                                                channel_name + ".py")
            core_channel_path = os.path.join(config.get_runtime_path(), 'core',
                                             channel_name + ".py")
            logger.info("[launcher.py] regular_channel_path=%s" %
                        regular_channel_path)
            logger.info("[launcher.py] core_channel_path=%s" %
                        core_channel_path)

            if channel_name == "buscador":
                import pelisalacarta.buscador as channel
            if channel_name == "personal" or channel_name == "personal2" or channel_name == "personal3" or channel_name == "personal4" or channel_name == "personal5":
                import pelisalacarta.channels.personal as channel
            elif os.path.exists(regular_channel_path):
                exec "import pelisalacarta.channels." + channel_name + " as channel"
            elif os.path.exists(regular_channel_path):
                exec "import tvalacarta.channels." + channel_name + " as channel"
            elif os.path.exists(core_channel_path):
                exec "from core import " + channel_name + " as channel"

            logger.info("[launcher.py] running channel %s %s" %
                        (channel.__name__, channel.__file__))

            generico = False
            # Esto lo he puesto asi porque el buscador puede ser generico o normal, esto estará asi hasta que todos los canales sean genericos
            if category == "Buscador_Generico":
                generico = True
            else:
                try:
                    generico = channel.isGeneric()
                except:
                    generico = False

            if not generico:
                logger.info("[launcher.py] xbmc native channel")
                if (action == "strm"):
                    from platformcode.xbmc import xbmctools
                    xbmctools.playstrm(params, url, category)
                else:
                    exec "channel." + action + "(params, url, category)"
            else:
                logger.info("[launcher.py] multiplatform channel")
                from core.item import Item
                item = Item(channel=channel_name,
                            title=title,
                            fulltitle=fulltitle,
                            url=url,
                            thumbnail=thumbnail,
                            plot=plot,
                            server=server,
                            category=category,
                            extra=extra,
                            subtitle=subtitle,
                            viewmode=viewmode,
                            show=show,
                            password=password,
                            fanart=fanart)
                '''
                if item.subtitle!="":
                    logger.info("[launcher.py] Downloading subtitle file "+item.subtitle)
                    from core import downloadtools
                    
                    ficherosubtitulo = os.path.join( config.get_data_path() , "subtitulo.srt" )
                    if os.path.exists(ficherosubtitulo):
                        os.remove(ficherosubtitulo)

                    downloadtools.downloadfile(item.subtitle, ficherosubtitulo )
                    config.set_setting("subtitulo","true")
                else:
                    logger.info("[launcher.py] No subtitle")
                '''
                from platformcode.xbmc import xbmctools

                if action == "play":
                    logger.info("[launcher.py] play")
                    # Si el canal tiene una acción "play" tiene prioridad
                    if hasattr(channel, 'play'):
                        logger.info(
                            "[launcher.py] executing channel 'play' method")
                        itemlist = channel.play(item)
                        if len(itemlist) > 0:
                            item = itemlist[0]
                            xbmctools.play_video(channel=channel_name,
                                                 server=item.server,
                                                 url=item.url,
                                                 category=item.category,
                                                 title=item.title,
                                                 thumbnail=item.thumbnail,
                                                 plot=item.plot,
                                                 extra=item.extra,
                                                 subtitle=item.subtitle,
                                                 video_password=item.password,
                                                 fulltitle=item.fulltitle,
                                                 Serie=item.show)
                        else:
                            import xbmcgui
                            ventana_error = xbmcgui.Dialog()
                            ok = ventana_error.ok(
                                "plugin", "No hay nada para reproducir")
                    else:
                        logger.info(
                            "[launcher.py] no channel 'play' method, executing core method"
                        )
                        xbmctools.play_video(channel=channel_name,
                                             server=item.server,
                                             url=item.url,
                                             category=item.category,
                                             title=item.title,
                                             thumbnail=item.thumbnail,
                                             plot=item.plot,
                                             extra=item.extra,
                                             subtitle=item.subtitle,
                                             video_password=item.password,
                                             fulltitle=item.fulltitle,
                                             Serie=item.show)

                elif action == "strm_detail" or action == "play_from_library":
                    logger.info("[launcher.py] play_from_library")

                    fulltitle = item.show + " " + item.title
                    elegido = Item(url="")

                    logger.info("item.server=#" + item.server + "#")
                    # Ejecuta find_videos, del canal o común
                    try:
                        itemlist = channel.findvideos(item)
                    except:
                        from servers import servertools
                        itemlist = servertools.find_video_items(item)

                    if len(itemlist) > 0:
                        #for item2 in itemlist:
                        #    logger.info(item2.title+" "+item2.subtitle)

                        # El usuario elige el mirror
                        opciones = []
                        for item in itemlist:
                            opciones.append(item.title)

                        import xbmcgui
                        dia = xbmcgui.Dialog()
                        seleccion = dia.select(
                            config.get_localized_string(30163), opciones)
                        elegido = itemlist[seleccion]

                        if seleccion == -1:
                            return
                    else:
                        elegido = item

                    # Ejecuta el método play del canal, si lo hay
                    try:
                        itemlist = channel.play(elegido)
                        item = itemlist[0]
                    except:
                        item = elegido
                    logger.info("Elegido %s (sub %s)" %
                                (item.title, item.subtitle))

                    from platformcode.xbmc import xbmctools
                    logger.info("subtitle=" + item.subtitle)
                    xbmctools.play_video(strmfile=True,
                                         channel=item.channel,
                                         server=item.server,
                                         url=item.url,
                                         category=item.category,
                                         title=item.title,
                                         thumbnail=item.thumbnail,
                                         plot=item.plot,
                                         extra=item.extra,
                                         subtitle=item.subtitle,
                                         video_password=item.password,
                                         fulltitle=fulltitle)

                elif action == "add_pelicula_to_library":
                    logger.info("[launcher.py] add_pelicula_to_library")
                    from platformcode.xbmc import library
                    # Obtiene el listado desde el que se llamó
                    library.savelibrary(titulo=item.fulltitle,
                                        url=item.url,
                                        thumbnail=item.thumbnail,
                                        server=item.server,
                                        plot=item.plot,
                                        canal=item.channel,
                                        category="Cine",
                                        Serie=item.show.strip(),
                                        verbose=False,
                                        accion="play_from_library",
                                        pedirnombre=False,
                                        subtitle=item.subtitle)

                elif action == "add_serie_to_library":
                    logger.info("[launcher.py] add_serie_to_library, show=#" +
                                item.show + "#")
                    from platformcode.xbmc import library
                    import xbmcgui

                    # Obtiene el listado desde el que se llamó
                    action = item.extra

                    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
                    if "###" in item.extra:
                        action = item.extra.split("###")[0]
                        item.extra = item.extra.split("###")[1]

                    exec "itemlist = channel." + action + "(item)"

                    # Progreso
                    pDialog = xbmcgui.DialogProgress()
                    ret = pDialog.create('pelisalacarta',
                                         'Añadiendo episodios...')
                    pDialog.update(0, 'Añadiendo episodio...')
                    totalepisodes = len(itemlist)
                    logger.info("[launcher.py] Total Episodios:" +
                                str(totalepisodes))
                    i = 0
                    errores = 0
                    nuevos = 0
                    for item in itemlist:
                        i = i + 1
                        pDialog.update(i * 100 / totalepisodes,
                                       'Añadiendo episodio...', item.title)
                        logger.info(
                            "[launcher.py] add_serie_to_library, title=" +
                            item.title)
                        if (pDialog.iscanceled()):
                            return

                        try:
                            #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
                            # Añade todos menos el que dice "Añadir esta serie..." o "Descargar esta serie..."
                            if item.action != "add_serie_to_library" and item.action != "download_all_episodes":
                                nuevos = nuevos + library.savelibrary(
                                    titulo=item.title,
                                    url=item.url,
                                    thumbnail=item.thumbnail,
                                    server=item.server,
                                    plot=item.plot,
                                    canal=item.channel,
                                    category="Series",
                                    Serie=item.show.strip(),
                                    verbose=False,
                                    accion="play_from_library",
                                    pedirnombre=False,
                                    subtitle=item.subtitle,
                                    extra=item.extra)
                        except IOError:
                            import sys
                            for line in sys.exc_info():
                                logger.error("%s" % line)
                            logger.info(
                                "[launcher.py]Error al grabar el archivo " +
                                item.title)
                            errores = errores + 1

                    pDialog.close()

                    # Actualizacion de la biblioteca
                    itemlist = []
                    if errores > 0:
                        itemlist.append(
                            Item(
                                title=
                                "ERROR, la serie NO se ha añadido a la biblioteca o lo ha hecho incompleta"
                            ))
                        logger.info("[launcher.py] No se pudo añadir " +
                                    str(errores) + " episodios")
                    else:
                        itemlist.append(
                            Item(title="La serie se ha añadido a la biblioteca"
                                 ))
                        logger.info("[launcher.py] Ningún error al añadir " +
                                    str(errores) + " episodios")

                    # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
                    #library.update(totalepisodes,errores,nuevos)
                    xbmctools.renderItems(itemlist, params, url, category)

                    #Lista con series para actualizar
                    nombre_fichero_config_canal = os.path.join(
                        config.get_library_path(), "series.xml")
                    if not os.path.exists(nombre_fichero_config_canal):
                        nombre_fichero_config_canal = os.path.join(
                            config.get_data_path(), "series.xml")

                    logger.info("nombre_fichero_config_canal=" +
                                nombre_fichero_config_canal)
                    if not os.path.exists(nombre_fichero_config_canal):
                        f = open(nombre_fichero_config_canal, "w")
                    else:
                        f = open(nombre_fichero_config_canal, "r")
                        contenido = f.read()
                        f.close()
                        f = open(nombre_fichero_config_canal, "w")
                        f.write(contenido)
                    from platformcode.xbmc import library
                    f.write(
                        library.title_to_folder_name(item.show) + "," +
                        item.url + "," + item.channel + "\n")
                    f.close()

                elif action == "download_all_episodes":
                    download_all_episodes(item, channel)

                elif action == "search":
                    logger.info("[launcher.py] search")
                    import xbmc
                    keyboard = xbmc.Keyboard("")
                    keyboard.doModal()
                    if (keyboard.isConfirmed()):
                        tecleado = keyboard.getText()
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item, tecleado)
                    else:
                        itemlist = []
                    xbmctools.renderItems(itemlist, params, url, category)

                else:
                    logger.info("[launcher.py] executing channel '" + action +
                                "' method")
                    if action != "findvideos":
                        exec "itemlist = channel." + action + "(item)"

                        #for item in itemlist:
                        #    logger.info("viemode="+item.viewmode)
                    else:

                        # Intenta ejecutar una posible funcion "findvideos" del canal
                        if hasattr(channel, 'findvideos'):
                            exec "itemlist = channel." + action + "(item)"
                        # Si no funciona, lanza el método genérico para detectar vídeos
                        else:
                            logger.info(
                                "[launcher.py] no channel 'findvideos' method, executing core method"
                            )
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)

                        from core import subtitletools
                        subtitletools.saveSubtitleName(item)

                    # Activa el modo biblioteca para todos los canales genéricos, para que se vea el argumento
                    import xbmcplugin
                    import sys
                    handle = sys.argv[1]
                    xbmcplugin.setContent(int(handle), "movies")

                    # Añade los items a la lista de XBMC
                    xbmctools.renderItems(itemlist, params, url, category)

    except urllib2.URLError, e:
        import traceback, sys
        from pprint import pprint
        exc_type, exc_value, exc_tb = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_tb)
        for line in lines:
            line_splits = line.split("\n")
            for line_split in line_splits:
                logger.error(line_split)

        import xbmcgui
        ventana_error = xbmcgui.Dialog()
        # Agarra los errores surgidos localmente enviados por las librerias internas
        if hasattr(e, 'reason'):
            logger.info("Razon del error, codigo: %d , Razon: %s" %
                        (e.reason[0], e.reason[1]))
            texto = config.get_localized_string(
                30050)  # "No se puede conectar con el sitio web"
            ok = ventana_error.ok("plugin", texto)
        # Agarra los errores con codigo de respuesta del servidor externo solicitado
        elif hasattr(e, 'code'):
            logger.info("codigo de error HTTP : %d" % e.code)
            texto = (
                config.get_localized_string(30051) % e.code
            )  # "El sitio web no funciona correctamente (error http %d)"
            ok = ventana_error.ok("plugin", texto)
コード例 #51
0
ファイル: playmax.py プロジェクト: d3v3l0p1n/mitvspain
def menu_info(item):
    logger.info()
    itemlist = []

    data = httptools.downloadpage(item.url).data
    data = re.sub(r"\n|\r|\t|\s{2}|&nbsp;|<br>", "", data)

    item.infoLabels["tmdb_id"] = scrapertools.find_single_match(
        data, '<a href="https://www.themoviedb.org/[^/]+/(\d+)')
    item.infoLabels["year"] = scrapertools.find_single_match(
        data, 'class="e_new">(\d{4})')
    item.infoLabels["plot"] = scrapertools.find_single_match(
        data, 'itemprop="description">([^<]+)</div>')
    item.infoLabels["genre"] = ", ".join(
        scrapertools.find_multiple_matches(
            data, '<a itemprop="genre"[^>]+>([^<]+)</a>'))
    if __modo_grafico__:
        tmdb.set_infoLabels_item(item, __modo_grafico__)

    action = "findvideos"
    title = "Ver enlaces"
    if item.contentType == "tvshow":
        action = "episodios"
        title = "Ver capítulos"
    itemlist.append(item.clone(action=action, title=title))

    carpeta = "CINE"
    tipo = "película"
    action = "add_pelicula_to_library"
    extra = ""
    if item.contentType == "tvshow":
        carpeta = "SERIES"
        tipo = "serie"
        action = "add_serie_to_library"
        extra = "episodios###library"

    library_path = config.get_library_path()
    if config.get_library_support():
        title = "Añadir %s a la biblioteca" % tipo
        if item.infoLabels["imdb_id"] and not library_path.lower().startswith(
                "smb://"):
            try:
                from core import filetools
                path = filetools.join(library_path, carpeta)
                files = filetools.walk(path)
                for dirpath, dirname, filename in files:
                    if item.infoLabels["imdb_id"] in dirpath:
                        namedir = dirpath.replace(path, '')[1:]
                        for f in filename:
                            if f != namedir + ".nfo" and f != "tvshow.nfo":
                                continue
                            from core import library
                            head_nfo, it = library.read_nfo(
                                filetools.join(dirpath, f))
                            canales = it.library_urls.keys()
                            canales.sort()
                            if "playmax" in canales:
                                canales.pop(canales.index("playmax"))
                                canales.insert(0, "[COLOR red]playmax[/COLOR]")
                            title = "%s ya en tu biblioteca. [%s] ¿Añadir?" % (
                                tipo.capitalize(), ",".join(canales))
                            break
            except:
                import traceback
                logger.error(traceback.format_exc())
                pass

        itemlist.append(
            item.clone(action=action,
                       title=title,
                       text_color=color5,
                       extra=extra))

    token_auth = config.get_setting("token_trakt", "tvmoviedb")
    if token_auth and item.infoLabels["tmdb_id"]:
        extra = "movie"
        if item.contentType != "movie":
            extra = "tv"
        itemlist.append(
            item.clone(channel="tvmoviedb",
                       title="[Trakt] Gestionar con tu cuenta",
                       action="menu_trakt",
                       extra=extra))
    itemlist.append(
        item.clone(channel="trailertools",
                   action="buscartrailer",
                   title="Buscar Tráiler",
                   text_color="magenta",
                   context=""))

    itemlist.append(item.clone(action="", title=""))
    ficha = scrapertools.find_single_match(item.url, '-f(\d+)-')
    if not ficha:
        ficha = scrapertools.find_single_match(item.url, 'f=(\d+)')

    itemlist.extend(acciones_fichas(item, sid, ficha, season=True))
    itemlist.append(
        item.clone(action="acciones_cuenta",
                   title="Añadir a una lista",
                   text_color=color3,
                   ficha=ficha))

    return itemlist
コード例 #52
0
ファイル: torrentlocura.py プロジェクト: d3v3l0p1n/mitvspain
def findvideos_enlaces(item):
    logger.info()
    itemlist = []
    check_epi2=""
    data = httptools.downloadpage(item.url).data
    
    url= scrapertools.find_single_match(data,'window.location.href = "([^"]+)"').strip()
        
    try:
     
     if not url.endswith(".torrent") :
         url= httptools.downloadpage(url,follow_redirects=False)
         url=url.headers.get("location")
         
         if not url.endswith(".torrent") :
            url= httptools.downloadpage(url,follow_redirects=False)
            url=url.headers.get("location")
     else:
         url= httptools.downloadpage(url,follow_redirects=False)
         url=url.headers.get("location") 	
     torrents_path = config.get_library_path()+'/torrents'
            
     if not os.path.exists(torrents_path):
        os.mkdir(torrents_path)
     try:
        urllib.URLopener.version = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0' 
        urllib.urlretrieve (url, torrents_path+"/temp.torrent")
        pepe = open( torrents_path+"/temp.torrent", "rb").read()
     except:
        pepe = ""
     if "used CloudFlare" in pepe:
        try:
            urllib.urlretrieve("http://anonymouse.org/cgi-bin/anon-www.cgi/"+url.strip(), torrents_path+"/temp.torrent")
            pepe = open( torrents_path+"/temp.torrent", "rb").read()
        except:
            pepe=""
     torrent = decode(pepe)

     try:
        name = torrent["info"]["name"]
        sizet = torrent["info"]['length']
        sizet=convert_size(sizet)
     except:
        name = "no disponible"
     try:
        check_video = scrapertools.find_multiple_matches(str(torrent["info"]["files"]),"'length': (\d+)}")
                
        size=max([int(i) for i in check_video])
            
        for file in torrent["info"]["files"]:
            manolo = "%r - %d bytes" % ("/".join(file["path"]), file["length"])
            if str(size) in manolo:
                video= manolo
        size =convert_size(size)
        ext_v= re.sub(r"-.*? bytes|.*?\[.*?\].|'|.*?COM.|.*?\[.*?\]|\(.*?\)|.*?\.","",video)
        try:
         os.remove(torrents_path+"/temp.torrent")
        except:
            pass
     except:
        size = sizet
        ext_v= re.sub(r"-.*? bytes|.*?\[.*?\].|'|.*?COM.|.*?\.es.|.*?\[.*?\]|.*?\(.*?\)\.|.*?\.","",name)
        try:
            os.remove(torrents_path+"/temp.torrent")
        except:
            pass
    except:
        size = "en estos momentos..."
        ext_v= "no disponible"
    if "rar" in ext_v:
        ext_v= ext_v +" -- No reproducible"
    if item.contentType!="movie":
          fanart=item.extra.split("|")[1]
    else:
        fanart=item.extra.split("|")[0]
    itemlist.append( Item(channel=item.channel, title = "[COLOR orangered][B]Torrent[/B][/COLOR] "+"[COLOR lemonchiffon]( Video [/COLOR]"+"[COLOR lemonchiffon]"+ext_v+"--"+size+" )[/COLOR]" , url=url,  action="play",server="torrent", thumbnail=item.extra.split("|")[4], fanart=fanart, folder=False) )

    if item.contentType!="movie" :
       if "Capitulos" in item.extra.split("|")[9]:
          epis= scrapertools.find_multiple_matches(item.extra.split("|")[9],'Capitulos (\d+) al (\d+)')
          for epi1, epi2 in epis:
              len_epis= int(epi2)-int(epi1)
              if len_epis==1:
                 extra = item.extra+"|"+epi1
                 check_epi2="ok"
                 title_info ="    Info Cap."+epi1
                 title_info = "[COLOR indianred]"+title_info+"[/COLOR]"
                 itemlist.append( Item(channel=item.channel, action="info_capitulos" , title=title_info , url=item.url, thumbnail=item.extra.split("|")[6], fanart=item.extra.split("|")[1], extra=extra, folder=False ))
              else:
                  check_epi2=""
                  epis_len=range(int(epi1),int(epi2)+1)
                  extra = item.extra+"|"+str(epis_len)
                  title_info ="    Info Capítulos"
                  title_info = "[COLOR indianred]"+title_info+"[/COLOR]"
                  itemlist.append( Item(channel=item.channel, action="capitulos" , title=title_info , url=item.url, thumbnail=item.extra.split("|")[6], fanart=item.extra.split("|")[1], extra =extra, folder=True ))
       else:
           
          title_info ="    Info"
          title_info = "[COLOR indianred]"+title_info+"[/COLOR]"
          if not ".png" in item.extra.split("|")[6]: 
             thumbnail= item.thumbnail
          else:
             thumbnail= item.extra.split("|")[6]
          itemlist.append( Item(channel=item.channel, action="info_capitulos" , title=title_info , url=item.url, thumbnail=thumbnail, fanart=item.extra.split("|")[1], extra=item.extra, folder=False ))
       if check_epi2=="ok":
          extra = item.extra+"|"+epi2
          title_info ="    Info Cap."+epi2
          title_info = "[COLOR indianred]"+title_info+"[/COLOR]"
          itemlist.append( Item(channel=item.channel, action="info_capitulos" , title=title_info , url=item.url, thumbnail=item.extra.split("|")[6], fanart=item.extra.split("|")[1], extra=extra, folder=False ))
    dd=scrapertools.find_single_match(data,'DESCARGAS DIRECTA(.*?)VER ONLINE')
    if dd:
       extra = item.extra+"|"+ dd
       itemlist.append( Item(channel=item.channel, title = "[COLOR floralwhite][B]Descarga directa y online[/B][/COLOR]"  , url=item.url,  action="dd_y_o", thumbnail="http://imgur.com/as7Ie6p.png", fanart=item.extra.split("|")[1],contentType=item.contentType, extra=extra, folder=True) )
    return itemlist