Example #1
0
def mostrar_perfil(item):
    logger.info()
    alfav = kodfavoritesData()

    itemlist = []

    i_perfil = item.i_perfil
    if not alfav.user_favorites[i_perfil]: return itemlist
    last_i = len(alfav.user_favorites[i_perfil]['items']) - 1

    ruta_runtime = config.get_runtime_path()

    for i_enlace, enlace in enumerate(alfav.user_favorites[i_perfil]['items']):

        it = Item().fromurl(enlace)
        it.context = [{
            'title':
            '[COLOR blue]' + config.get_localized_string(70617) + '[/COLOR]',
            'channel':
            item.channel,
            'action':
            'acciones_enlace',
            'i_enlace':
            i_enlace,
            'i_perfil':
            i_perfil
        }]

        it.plot += '[CR][CR][COLOR blue]' + config.get_localized_string(
            70724
        ) + ':[/COLOR] ' + it.channel + ' [COLOR blue]' + config.get_localized_string(
            60266) + ':[/COLOR] ' + it.action
        if it.extra != '': it.plot += ' [COLOR blue]Extra:[/COLOR] ' + it.extra
        it.plot += '[CR][COLOR blue]Url:[/COLOR] ' + it.url if isinstance(
            it.url, str) else '...'
        if it.date_added != '':
            it.plot += '[CR][COLOR blue]' + config.get_localized_string(
                70469) + ':[/COLOR] ' + it.date_added

        # Si no es una url, ni tiene la ruta del sistema, convertir el path ya que se habrá copiado de otro dispositivo.
        # Sería más óptimo que la conversión se hiciera con un menú de importar, pero de momento se controla en run-time.
        if it.thumbnail and '://' not in it.thumbnail and not it.thumbnail.startswith(
                ruta_runtime):
            ruta, fichero = filetools.split(it.thumbnail)
            if ruta == '' and fichero == it.thumbnail:  # en linux el split con un path de windows no separa correctamente
                ruta, fichero = filetools.split(it.thumbnail.replace(
                    '\\', '/'))
            if 'channels' in ruta and 'thumb' in ruta:
                it.thumbnail = filetools.join(ruta_runtime, 'resources',
                                              'media', 'channels', 'thumb',
                                              fichero)
            elif 'themes' in ruta and 'default' in ruta:
                it.thumbnail = filetools.join(ruta_runtime, 'resources',
                                              'media', 'themes', 'default',
                                              fichero)

        itemlist.append(it)

    return itemlist
Example #2
0
def mostrar_perfil(item):
    logger.info()
    alfav = KodfavouritesData()

    itemlist = []

    i_perfil = item.i_perfil
    if not alfav.user_favorites[i_perfil]: return itemlist
    last_i = len(alfav.user_favorites[i_perfil]['items']) - 1

    ruta_runtime = config.get_runtime_path()

    for i_enlace, enlace in enumerate(alfav.user_favorites[i_perfil]['items']):

        it = Item().fromurl(enlace)
        it.context = [{
            'title':
            '[COLOR blue]' + config.get_localized_string(70617) + '[/COLOR]',
            'channel':
            item.channel,
            'action':
            'acciones_enlace',
            'i_enlace':
            i_enlace,
            'i_perfil':
            i_perfil
        }]

        it.plot += '[CR][CR][COLOR blue]' + config.get_localized_string(
            70724
        ) + ':[/COLOR] ' + it.channel + ' [COLOR blue]' + config.get_localized_string(
            60266) + ':[/COLOR] ' + it.action
        if it.extra != '': it.plot += ' [COLOR blue]Extra:[/COLOR] ' + it.extra
        it.plot += '[CR][COLOR blue]Url:[/COLOR] ' + it.url if isinstance(
            it.url, str) else '...'
        if it.date_added != '':
            it.plot += '[CR][COLOR blue]' + config.get_localized_string(
                70469) + ':[/COLOR] ' + it.date_added

        # If it is not a url, nor does it have the system path, convert the path since it will have been copied from another device.
        # It would be more optimal if the conversion was done with an import menu, but at the moment it is controlled in run-time.
        if it.thumbnail and '://' not in it.thumbnail and not it.thumbnail.startswith(
                ruta_runtime):
            ruta, fichero = filetools.split(it.thumbnail)
            if ruta == '' and fichero == it.thumbnail:  # in linux the split with a windows path does not separate correctly
                ruta, fichero = filetools.split(it.thumbnail.replace(
                    '\\', '/'))
            if 'channels' in ruta and 'thumb' in ruta:
                it.thumbnail = filetools.join(ruta_runtime, 'resources',
                                              'media', 'channels', 'thumb',
                                              fichero)
            elif 'themes' in ruta and 'default' in ruta:
                it.thumbnail = filetools.join(ruta_runtime, 'resources',
                                              'media', 'themes', 'default',
                                              fichero)

        itemlist.append(it)

    return itemlist
Example #3
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])
Example #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])
Example #5
0
    def extract(self, file, dir, folder_to_extract="", overwrite_question=False, backup=False):
        logger.info("file= %s" % file)
        logger.info("dir= %s" % dir)

        if not dir.endswith(':') and not filetools.exists(dir):
            filetools.mkdir(dir)

        zf = zipfile.ZipFile(filetools.file_open(file, vfs=False))
        if not folder_to_extract:
            self._createstructure(file, dir)
        num_files = len(zf.namelist())

        for nameo in zf.namelist():
            name = nameo.replace(':', '_').replace('<', '_').replace('>', '_').replace('|', '_').replace('"', '_').replace('?', '_').replace('*', '_')
            logger.info("name=%s" % nameo)
            if not name.endswith('/'):
                logger.info("it's not a directory")
                try:
                    (path, filename) = filetools.split(filetools.join(dir, name))
                    logger.info("path=%s" % path)
                    logger.info("name=%s" % name)
                    if folder_to_extract:
                        if path != filetools.join(dir, folder_to_extract):
                            break
                    else:
                        filetools.mkdir(path)
                except:
                    pass
                if folder_to_extract:
                    outfilename = filetools.join(dir, filename)

                else:
                    outfilename = filetools.join(dir, name)
                logger.info("outfilename=%s" % outfilename)
                try:
                    if filetools.exists(outfilename) and overwrite_question:
                        from platformcode import platformtools
                        dyesno = platformtools.dialog_yesno("File already exists "," File %s to unzip already exists, do you want to overwrite it?" % filetools.basename(outfilename))
                        if not dyesno:
                            break
                        if backup:
                            import time
                            hora_folder = "Backup [%s]" % time.strftime("%d-%m_%H-%M", time.localtime())
                            backup = filetools.join(config.get_data_path(), 'backups', hora_folder, folder_to_extract)
                            if not filetools.exists(backup):
                                filetools.mkdir(backup)
                            filetools.copy(outfilename, filetools.join(backup, filetools.basename(outfilename)))

                    if not filetools.write(outfilename, zf.read(nameo), silent=True, vfs=VFS):  #TRUNCA en FINAL en Kodi 19 con VFS
                        logger.error("File error " + nameo)
                except:
                    import traceback
                    logger.error(traceback.format_exc())
                    logger.error("File error " + nameo)

        try:
            zf.close()
        except:
            logger.info("Error closing .zip " + file)
Example #6
0
def find_file(hash):
    path = xbmc.translatePath(config.get_setting('downloadlistpath'))
    files = filetools.listdir(path)
    for f in files:
        filepath = filetools.join(path, f)
        json = jsontools.load(filetools.read(filepath))
        if ('downloadServer' in json and 'url' in json['downloadServer'] and hash in json['downloadServer']['url']) or ('url' in json and hash in json['url']):
            break
    return filetools.split(filepath)[-1]
Example #7
0
def rename(File):
    jsonPath = xbmc.translatePath(config.get_setting('downloadlistpath'))
    json = jsontools.load(open(filetools.join(jsonPath, File), "r").read())
    filePath = filetools.join(xbmc.translatePath(config.get_setting('downloadpath')), json['downloadFilename'])

    if json['infoLabels']['mediatype'] == 'movie':
        if filetools.isdir(filePath):
            extension = ''
            files = filetools.listdir(filePath)
            oldName = json['downloadFilename']
            newName = json['backupFilename']
            for f in files:
                ext = os.path.splitext(f)[-1]
                if ext in extensions_list: extension = ext
                filetools.rename(filetools.join(filePath, f), f.replace(oldName, newName))
            filetools.rename(filePath, newName)
            jsontools.update_node(filetools.join(newName, newName + extension), File, 'downloadFilename', jsonPath)

        else:
            oldName = json['downloadFilename']
            newName = json['backupFilename'] + os.path.splitext(oldName)[-1]
            filetools.rename(filePath, newName)
            jsontools.update_node(newName, File, 'downloadFilename', jsonPath)
    else:
        sep = '/' if filePath.lower().startswith("smb://") else os.sep
        FolderName = json['backupFilename'].split(sep)[0]
        Title = re.sub(r'(\s*\[[^\]]+\])', '', FolderName)
        if filetools.isdir(filePath):
            files = filetools.listdir(filePath)
            file_dict = {}
            for f in files:
                title = process_filename(f, Title, ext=False)
                ext = os.path.splitext(f)[-1]
                name = os.path.splitext(f)[0]
                if title not in file_dict and ext in extensions_list:
                    file_dict[title] = name

            for title, name in file_dict.items():
                for f in files:
                    if name in f:
                        filetools.rename(filetools.join(filePath, f), f.replace(name, title))

            filetools.rename(filePath, FolderName)
            jsontools.update_node(FolderName, File, 'downloadFilename', jsonPath)
        else:
            filename = filetools.split(filePath)[-1]
            title = process_filename(filename, Title)
            NewFolder = filetools.join(config.get_setting('downloadpath'), FolderName)
            if not filetools.isdir(NewFolder):
                filetools.mkdir(NewFolder)
            from_folder = filetools.join(config.get_setting('downloadpath'), filename)
            to_folder = filetools.join(config.get_setting('downloadpath'), FolderName, title)
            filetools.move(from_folder, to_folder)
            jsontools.update_node(filetools.join(FolderName, title), File, 'downloadFilename', jsonPath)
Example #8
0
def set_Subtitle():
    logger.info()

    exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass"]
    subtitle_folder_path = filetools.join(config.get_data_path(), "subtitles")

    subtitle_type = config.get_setting("subtitle_type")

    if subtitle_type == "2":
        subtitle_path = config.get_setting("subtitlepath_file")
        logger.info("Con subtitulo : " + subtitle_path)
        xbmc.Player().setSubtitles(subtitle_path)
    else:
        if subtitle_type == "0":
            subtitle_path = config.get_setting("subtitlepath_folder")
            if subtitle_path == "":
                subtitle_path = subtitle_folder_path
                config.set_setting("subtitlepath_folder", subtitle_path)
        else:
            subtitle_path = config.get_setting("subtitlepath_keyboard")
            long = len(subtitle_path)
            if long > 0:
                if subtitle_path.startswith("http") or subtitle_path[
                        long - 4, long] in exts:
                    logger.info("Con subtitulo : " + subtitle_path)
                    xbmc.Player().setSubtitles(subtitle_path)
                    return
            else:
                subtitle_path = subtitle_folder_path
                config.set_setting("subtitlepath_keyboard", subtitle_path)

        import glob

        subtitle_name = config.get_setting("subtitle_name").replace("amp;", "")
        tvshow_title, season, episode = regex_tvshow(False, subtitle_name)
        try:
            if episode != "":
                Subnames = glob.glob(
                    filetools.join(
                        subtitle_path, "Tvshows", tvshow_title, "%s %sx%s" %
                        (tvshow_title, season, episode) + "*.??.???"))
            else:
                Subnames = glob.glob(
                    filetools.join(subtitle_path, "Movies",
                                   subtitle_name + "*.??.???"))
            for Subname in Subnames:
                if os.path.splitext(Subname)[1] in exts:
                    logger.info("Con subtitulo : " +
                                filetools.split(Subname)[1])
                    xbmc.Player().setSubtitles((Subname))
        except:
            logger.error("error al cargar subtitulos")
Example #9
0
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])
Example #10
0
def remove_files( download, torrent_file, video_file, ses, h, ren_video_file="", item={} ):
    dialog_view = False
    torrent = False

    if os.path.isfile( torrent_file ):
        dialog_view = True
        torrent = True

    if download > 0:
        dialog_view = True
    if bkg_user and not extracted_rar:
        dialog_view = False
    
    if erase_file_path and erase_file_path != \
                            os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
        ren_video_file = erase_file_path
    if filetools.isfile(ren_video_file) and filetools.split(ren_video_file)[0] != \
                            os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
        ren_video_file = filetools.split(ren_video_file)[0]
    elif filetools.isdir(ren_video_file) and ren_video_file == \
                            os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
        ren_video_file = ''

    # Actualizado .json de control de descargas
    if not torrent_file or item.downloadProgress == 0:
        item.downloadProgress = 0
        #log("##### .torrent borrado: %s" % erase_file_path)
    else:
        item.downloadProgress = 100
    torr.update_control(item, function='mct_remove_files')
    if item.downloadStatus in [2, 4] and item.downloadProgress in [100]:
        dialog_view = False
    
    if dialog_view and ren_video_file:
        if h.status().num_pieces >= tot_piece_set:
            d = xbmcgui.Dialog()
            ok = d.yesno(msg_header, '¿Borrarmos los archivos descargados? (completos)' + '\n' +  video_file)
        else:
            ok = True

        # -- SI -------------------------------------------------
        if ok:
            # -- Borrar archivo - torrent -----------------------
            if torrent:
                try:
                    os.remove( torrent_file )
                except:
                    pass
            # -- Borrar carpeta/archivos y sesión - vídeo -------
            try:
                ses.remove_torrent( h, 1 )
                ses_lt = False
            except:
                ses_lt = False
            try:
                if os.path.isdir(ren_video_file):
                    filetools.rmdirtree(ren_video_file, silent=True)
                elif os.path.exists(ren_video_file) and os.path.isfile(ren_video_file): 
                    os.remove(ren_video_file)
                log("##### erase_file_path: %s" % ren_video_file)
            except:
                log("##### erase_file_path: %s" % ren_video_file)

            log("### End session #########")
        else:
            # -- Borrar sesión ----------------------------------
            try:
                ses.remove_torrent( h )
                ses_lt = False
            except:
                ses_lt = False
            log("### End session #########")
    else:
        # -- Borrar sesión --------------------------------------
        try:
            ses.remove_torrent( h )
            ses_lt = False
        except:
            ses_lt = False
        # -- Borrar archivo - torrent -----------------------
        if torrent:
            try:
                os.remove( torrent_file )
            except:
                pass
        log("### End session #########")
        
    filetools.remove(filetools.join( DOWNLOAD_PATH , "MCT-torrent-videos",  '.' + \
                os.path.splitext(filetools.basename(torrent_file))[0].lower() + '.parts'), silent=True)

    return                        
Example #11
0
def remove_files( download, torrent_file, video_file, ses, h, ren_video_file="", erase_file_path='' ):
    dialog_view = False
    torrent = False

    if os.path.isfile( torrent_file ):
        dialog_view = True
        torrent = True

    if download > 0:
        dialog_view = True
    if bkg_user and not extracted_rar:
        dialog_view = False

    if erase_file_path and erase_file_path != os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
        ren_video_file = erase_file_path
    if filetools.isfile(ren_video_file) and filetools.split(ren_video_file)[0] !=  os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
        ren_video_file = filetools.split(ren_video_file)[0]
    elif filetools.isdir(ren_video_file) and ren_video_file ==  os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
        ren_video_file = ''

    if dialog_view and ren_video_file:
        if h.status().num_pieces >= tot_piece_set:
            d = xbmcgui.Dialog()
            ok = d.yesno(msg_header, config.get_localized_string(30031), video_file)
        else:
            ok = True

        # -- SI -------------------------------------------------
        if ok:
            # -- Borrar archivo - torrent -----------------------
            if torrent:
                try:
                    os.remove( torrent_file )
                except:
                    pass
            # -- Borrar carpeta/archivos y sesión - vídeo -------
            try:
                ses.remove_torrent( h, 1 )
                ses_lt = False
            except:
                ses_lt = False
            try:
                if os.path.isdir(ren_video_file):
                    filetools.rmdirtree(ren_video_file, silent=True)
                elif os.path.exists(ren_video_file) and os.path.isfile(ren_video_file):
                    os.remove(ren_video_file)
                log("##### erase_file_path: %s" % ren_video_file)
            except:
                log("##### erase_file_path: %s" % ren_video_file)

            log("### End session #########")
        else:
            # -- Borrar sesión ----------------------------------
            try:
                ses.remove_torrent( h )
                ses_lt = False
            except:
                ses_lt = False
            log("### End session #########")
    else:
        # -- Borrar sesión --------------------------------------
        try:
            ses.remove_torrent( h )
            ses_lt = False
        except:
            ses_lt = False
        # -- Borrar archivo - torrent -----------------------
        if torrent:
            try:
                os.remove( torrent_file )
            except:
                pass
        log("### End session #########")

    return
Example #12
0
def findvideos(item):
    from core import autoplay
    from platformcode import platformtools

    logger.debug()
    # logger.debug("item:\n" + item.tostring('\n'))
    videolibrarytools.check_renumber_options(item)
    itemlist = []
    list_canales = {}
    item_local = None

    # Disable autoplay
    # autoplay.set_status(False)

    if not item.contentTitle or not item.strm_path:
        logger.debug("Unable to search for videos due to lack of parameters")
        return []

    if item.contentEpisodeNumber:
        content_title = str(item.contentSeason) + 'x' + (str(item.contentEpisodeNumber) if item.contentEpisodeNumber > 9 else '0' + str(item.contentEpisodeNumber))
    else:
        content_title = item.contentTitle.strip().lower()
    if item.contentType == 'movie':
        item.strm_path = filetools.join(videolibrarytools.MOVIES_PATH, item.strm_path)
        path_dir = filetools.dirname(item.strm_path)
        item.nfo = filetools.join(path_dir, filetools.basename(path_dir) + ".nfo")
    else:
        item.strm_path = filetools.join(videolibrarytools.TVSHOWS_PATH, item.strm_path)
        path_dir = filetools.dirname(item.strm_path)
        item.nfo = filetools.join(path_dir, 'tvshow.nfo')

    for fd in filetools.listdir(path_dir):
        if fd.endswith('.json'):
            contenido, nom_canal = fd[:-6].split('[')
            if (contenido.startswith(content_title) or item.contentType == 'movie') and nom_canal not in list(list_canales.keys()):
                list_canales[nom_canal] = filetools.join(path_dir, fd)

    num_canales = len(list_canales)

    if 'downloads' in list_canales:
        json_path = list_canales['downloads']
        item_json = Item().fromjson(filetools.read(json_path))
        item_json.contentChannel = "local"
        # Support for relative paths in downloads
        if filetools.is_relative(item_json.url):
            item_json.url = filetools.join(videolibrarytools.VIDEOLIBRARY_PATH, item_json.url)

        del list_canales['downloads']

        # Check that the video has not been deleted
        if filetools.exists(item_json.url):
            item_local = item_json.clone(action='play')
            itemlist.append(item_local)
        else:
            num_canales -= 1

    filtro_canal = ''
    if num_canales > 1 and config.get_setting("ask_channel", "videolibrary"):
        opciones = [config.get_localized_string(70089) % k.capitalize() for k in list(list_canales.keys())]
        opciones.insert(0, config.get_localized_string(70083))
        if item_local:
            opciones.append(item_local.title)

        index = platformtools.dialog_select(config.get_localized_string(30163), opciones)
        if index < 0:
            return []

        elif item_local and index == len(opciones) - 1:
            filtro_canal = 'downloads'
            platformtools.play_video(item_local)

        elif index > 0:
            filtro_canal = opciones[index].replace(config.get_localized_string(70078), "").strip()
            itemlist = []

    all_videolibrary = []
    for nom_canal, json_path in list(list_canales.items()):
        if filtro_canal and filtro_canal != nom_canal.capitalize():
            continue

        item_canal = Item()

        # We import the channel of the selected part
        try:
            if nom_canal == 'community':
                channel = __import__('specials.%s' % nom_canal, fromlist=["channels.%s" % nom_canal])
            else:
                channel = __import__('channels.%s' % nom_canal, fromlist=["channels.%s" % nom_canal])
        except ImportError:
            exec("import channels." + nom_canal + " as channel")
        except:
            dead_list = []
            zombie_list = []

            if nom_canal not in dead_list and nom_canal not in zombie_list: confirm = platformtools.dialog_yesno(config.get_localized_string(30131), config.get_localized_string(30132) % nom_canal.upper() + '\n' + config.get_localized_string(30133))
            elif nom_canal in zombie_list: confirm = False
            else: confirm = True

            if confirm:
                # delete the channel from all movie and tvshow
                from past.utils import old_div
                num_enlaces = 0
                dialog = platformtools.dialog_progress(config.get_localized_string(30131), config.get_localized_string(60005) % nom_canal)
                if not all_videolibrary:
                    all_videolibrary = list_movies(Item()) + list_tvshows(Item())
                for n, it in enumerate(all_videolibrary):
                    if nom_canal in it.library_urls:
                        dead_item = Item(multichannel=len(it.library_urls) > 1,
                                         contentType=it.contentType,
                                         dead=nom_canal,
                                         path=filetools.split(it.nfo)[0],
                                         nfo=it.nfo,
                                         library_urls=it.library_urls,
                                         infoLabels={'title': it.contentTitle})
                        num_enlaces += delete(dead_item)
                    dialog.update(old_div(100*n, len(all_videolibrary)))

                dialog.close()
                msg_txt = config.get_localized_string(70087) % (num_enlaces, nom_canal)
                logger.info(msg_txt)
                platformtools.dialog_notification(config.get_localized_string(30131), msg_txt)
                platformtools.itemlist_refresh()

                if nom_canal not in dead_list:
                    dead_list.append(nom_canal)
                continue
            else:
                if nom_canal not in zombie_list:
                    zombie_list.append(nom_canal)

            if len(dead_list) > 0:
                for nom_canal in dead_list:
                    if nom_canal in item.library_urls:
                        del item.library_urls[nom_canal]

        item_json = Item().fromjson(filetools.read(json_path))
        list_servers = []

        try:
            # FILTERTOOLS
            # if the channel has a filter, the name it has saved is passed to it so that it filters correctly.
            if "list_language" in item_json:
                # if it comes from the addon video library
                if "library_filter_show" in item:
                    item_json.show = item.library_filter_show.get(nom_canal, "")

            # We run find_videos, from the channel or common
            item_json.contentChannel = 'videolibrary'
            item_json.play_from = item.play_from
            item_json.nfo = item.nfo
            item_json.strm_path = item.strm_path
            if hasattr(channel, 'findvideos'):
                from core import servertools
                if item_json.videolibray_emergency_urls:
                    del item_json.videolibray_emergency_urls
                list_servers = getattr(channel, 'findvideos')(item_json)
            elif item_json.action == 'play':
                from platformcode import platformtools
                # autoplay.set_status(True)
                item_json.contentChannel = item_json.channel
                item_json.channel = "videolibrary"
                platformtools.play_video(item_json)
                return ''
            else:
                from core import servertools
                list_servers = servertools.find_video_items(item_json)
        except Exception as ex:
            logger.error("The findvideos function for the channel %s failed" % nom_canal)
            template = "An exception of type %s occured. Arguments:\n%r"
            message = template % (type(ex).__name__, ex.args)
            logger.error(message)
            logger.error(traceback.format_exc())

        # Change the title to the servers adding the name of the channel in front and the infoLabels and the images of the item if the server does not have
        for server in list_servers:
            server.contentChannel = server.channel
            server.channel = "videolibrary"
            server.nfo = item.nfo
            server.strm_path = item.strm_path
            server.play_from = item.play_from

            # Kodi 18 Compatibility - Prevents wheel from spinning around in Direct Links
            if server.action == 'play':
                server.folder = False

            # Channel name is added if desired
            if config.get_setting("quit_channel_name", "videolibrary") == 0:
                server.title = "%s: %s" % (nom_canal.capitalize(), server.title)

            if not server.thumbnail:
                server.thumbnail = item.thumbnail

            # logger.debug("server:\n%s" % server.tostring('\n'))
            itemlist.append(server)

    if autoplay.play_multi_channel(item, itemlist):  # hideserver
        return []

    add_download_items(item, itemlist)
    return itemlist
def mark_content_as_watched_on_kodi(item, value=1):
    """
    marca el contenido como visto o no visto 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'))
    payload_f = ''

    if item.contentType == "movie":
        movieid = 0
        payload = {"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies",
                   "params": {"properties": ["title", "playcount", "originaltitle", "file"]},
                   "id": 1}

        data = get_data(payload)
        if 'result' in data and "movies" in data['result']:

            filename = filetools.basename(item.strm_path)
            head, tail = filetools.split(filetools.split(item.strm_path)[0])
            path = filetools.join(tail, filename)

            for d in data['result']['movies']:
                if d['file'].replace("/", "\\").endswith(path.replace("/", "\\")):
                    # logger.debug("marco la pelicula como vista")
                    movieid = d['movieid']
                    break

        if movieid != 0:
            payload_f = {"jsonrpc": "2.0", "method": "VideoLibrary.SetMovieDetails", "params": {
                "movieid": movieid, "playcount": value}, "id": 1}

    else:  # item.contentType != 'movie'
        episodeid = 0
        payload = {"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes",
                   "params": {"properties": ["title", "playcount", "showtitle", "file", "tvshowid"]},
                   "id": 1}

        data = get_data(payload)
        if 'result' in data and "episodes" in data['result']:

            filename = filetools.basename(item.strm_path)
            head, tail = filetools.split(filetools.split(item.strm_path)[0])
            path = filetools.join(tail, filename)

            for d in data['result']['episodes']:

                if d['file'].replace("/", "\\").endswith(path.replace("/", "\\")):
                    # logger.debug("marco el episodio como visto")
                    episodeid = d['episodeid']
                    break

        if episodeid != 0:
            payload_f = {"jsonrpc": "2.0", "method": "VideoLibrary.SetEpisodeDetails", "params": {
                "episodeid": episodeid, "playcount": value}, "id": 1}

    if payload_f:
        # Marcar como visto
        data = get_data(payload_f)
        # logger.debug(str(data))
        if data['result'] != 'OK':
            logger.error("ERROR al poner el contenido como visto")
Example #14
0
def get_results(nfo_path, root, Type, local=False):
    dead_list = []
    zombie_list = []
    value = 0
    if Type == 'movie': folder = "folder_movies"
    else: folder = "folder_tvshows"

    if filetools.exists(nfo_path):
        # We synchronize the episodes seen from the Kodi video library with that of KoD
        from platformcode import xbmc_videolibrary
        xbmc_videolibrary.mark_content_as_watched_on_kod(nfo_path)
        head_nfo, item = videolibrarytools.read_nfo(nfo_path)

        # If you have not read the .nfo well, we will proceed to the next
        if not item:
            logger.error('.nfo erroneous in ' + str(nfo_path))
            return Item(), 0

        if len(item.library_urls) > 1: multichannel = True
        else: multichannel = False

        # Verify the existence of the channels. If the channel does not exist, ask yourself if you want to remove the links from that channel.

        for canal in item.library_urls:
            try:
                if canal in ['community', 'downloads']: channel_verify = __import__('specials.%s' % canal, fromlist=["channels.%s" % canal])
                else: channel_verify = __import__('channels.%s' % canal, fromlist=["channels.%s" % canal])
                logger.debug('Channel %s seems correct' % channel_verify)
            except:
                dead_item = Item(multichannel=multichannel,
                                 contentType='tvshow',
                                 dead=canal,
                                 path=filetools.split(nfo_path)[0],
                                 nfo=nfo_path,
                                 library_urls=item.library_urls,
                                 infoLabels={'title': item.contentTitle})

                if canal not in dead_list and canal not in zombie_list: confirm = platformtools.dialog_yesno(config.get_localized_string(30131), config.get_localized_string(30132) % canal.upper() + '\n' + config.get_localized_string(30133))
                elif canal in zombie_list: confirm = False
                else: confirm = True

                if confirm:
                    delete(dead_item)
                    if canal not in dead_list:
                        dead_list.append(canal)
                    continue
                else:
                    if canal not in zombie_list:
                        zombie_list.append(canal)

        if len(dead_list) > 0:
            for canal in dead_list:
                if canal in item.library_urls:
                    del item.library_urls[canal]

        # continue loading the elements of the video library
        if Type == 'movie':
            item.path = filetools.split(nfo_path)[0]
            item.nfo = nfo_path
            sep = '/' if '/' in nfo_path else '\\'
            item.extra = filetools.join(config.get_setting("videolibrarypath"), config.get_setting(folder), item.path.split(sep)[-1])
            strm_path = item.strm_path.replace("\\", "/").rstrip("/")
            if not item.thumbnail: item.thumbnail = item.infoLabels['thumbnail']
            if '/' in item.path: item.strm_path = strm_path
            # If strm has been removed from kodi library, don't show it
            if not filetools.exists(filetools.join(item.path, filetools.basename(strm_path))) and not local: return Item(), 0

            # Contextual menu: Mark as seen / not seen
            visto = item.library_playcounts.get(item.path.split(sep)[0], 0)
            item.infoLabels["playcount"] = visto
            if visto > 0:
                seen_text = config.get_localized_string(60016)
                counter = 0
            else:
                seen_text = config.get_localized_string(60017)
                counter = 1

            # Context menu: Delete series / channel
            channels_num = len(item.library_urls)
            if "downloads" in item.library_urls: channels_num -= 1
            if channels_num > 1: delete_text = config.get_localized_string(60018)
            else: delete_text = config.get_localized_string(60019)

            item.context = [{"title": seen_text, "action": "mark_content_as_watched", "channel": "videolibrary",  "playcount": counter},
                            {"title": delete_text, "action": "delete", "channel": "videolibrary", "multichannel": multichannel}]
        else:
            # Sometimes it gives random errors, for not finding the .nfo. Probably timing issues
            try:
                item.title = item.contentTitle
                item.path = filetools.split(nfo_path)[0]
                item.nfo = nfo_path
                sep = '/' if '/' in nfo_path else '\\'
                item.extra = filetools.join(config.get_setting("videolibrarypath"), config.get_setting(folder), item.path.split(sep)[-1])
                # Contextual menu: Mark as seen / not seen
                visto = item.library_playcounts.get(item.contentTitle, 0)
                item.infoLabels["playcount"] = visto
                logger.info('item\n' + str(item))
                if visto > 0:
                    seen_text = config.get_localized_string(60020)
                    counter = 0
                else:
                    seen_text = config.get_localized_string(60021)
                    counter = 1

            except:
                logger.error('Not find: ' + str(nfo_path))
                logger.error(traceback.format_exc())
                return Item(), 0

            # Context menu: Automatically search for new episodes or not
            if item.active and int(item.active) > 0:
                update_text = config.get_localized_string(60022)
                value = 0
            else:
                update_text = config.get_localized_string(60023)
                value = 1
                item.title += " [B]" + u"\u2022" + "[/B]"

            # Context menu: Delete series / channel
            channels_num = len(item.library_urls)
            if "downloads" in item.library_urls: channels_num -= 1
            if channels_num > 1: delete_text = config.get_localized_string(60024)
            else: delete_text = config.get_localized_string(60025)

            item.context = [{"title": seen_text, "action": "mark_content_as_watched", "channel": "videolibrary", "playcount": counter},
                            {"title": update_text, "action": "mark_tvshow_as_updatable", "channel": "videolibrary", "active": value},
                            {"title": delete_text, "action": "delete", "channel": "videolibrary", "multichannel": multichannel},
                            {"title": config.get_localized_string(70269), "action": "update_tvshow", "channel": "videolibrary"}]
            if item.local_episodes_path == "": item.context.append({"title": config.get_localized_string(80048), "action": "add_local_episodes", "channel": "videolibrary"})
            else: item.context.append({"title": config.get_localized_string(80049), "action": "remove_local_episodes", "channel": "videolibrary"})
    else: item = Item()
    return item, value
Example #15
0
def get_environment():
    """
    Devuelve las variables de entorno del OS, de Kodi y de Alfa más habituales,
    necesarias para el diagnóstico de fallos 
    """

    try:
        import base64
        import ast

        environment = config.get_platform(full_version=True)
        environment['num_version'] = str(environment['num_version'])
        environment['python_version'] = str(platform.python_version())

        environment['os_release'] = str(platform.release())
        if xbmc.getCondVisibility("system.platform.Windows"):
            try:
                if platform._syscmd_ver()[2]:
                    environment['os_release'] = str(platform._syscmd_ver()[2])
            except:
                pass
        environment['prod_model'] = ''
        if xbmc.getCondVisibility("system.platform.Android"):
            environment['os_name'] = 'Android'
            try:
                for label_a in subprocess.check_output('getprop').split('\n'):
                    if 'build.version.release' in label_a:
                        environment['os_release'] = str(
                            scrapertools.find_single_match(
                                label_a, ':\s*\[(.*?)\]$'))
                    if 'product.model' in label_a:
                        environment['prod_model'] = str(
                            scrapertools.find_single_match(
                                label_a, ':\s*\[(.*?)\]$'))
            except:
                try:
                    for label_a in filetools.read(os.environ['ANDROID_ROOT'] +
                                                  '/build.prop').split():
                        if 'build.version.release' in label_a:
                            environment['os_release'] = str(
                                scrapertools.find_single_match(
                                    label_a, '=(.*?)$'))
                        if 'product.model' in label_a:
                            environment['prod_model'] = str(
                                scrapertools.find_single_match(
                                    label_a, '=(.*?)$'))
                except:
                    pass

        elif xbmc.getCondVisibility("system.platform.Linux.RaspberryPi"):
            environment['os_name'] = 'RaspberryPi'
        else:
            environment['os_name'] = str(platform.system())

        environment['machine'] = str(platform.machine())
        environment['architecture'] = str(sys.maxsize > 2**32 and "64-bit"
                                          or "32-bit")
        environment['language'] = str(xbmc.getInfoLabel('System.Language'))

        environment['cpu_usage'] = str(xbmc.getInfoLabel('System.CpuUsage'))

        environment['mem_total'] = str(
            xbmc.getInfoLabel('System.Memory(total)')).replace('MB',
                                                               '').replace(
                                                                   'KB', '')
        environment['mem_free'] = str(
            xbmc.getInfoLabel('System.Memory(free)')).replace('MB',
                                                              '').replace(
                                                                  'KB', '')
        if not environment['mem_total'] or not environment['mem_free']:
            try:
                if environment['os_name'].lower() == 'windows':
                    kernel32 = ctypes.windll.kernel32
                    c_ulong = ctypes.c_ulong
                    c_ulonglong = ctypes.c_ulonglong

                    class MEMORYSTATUS(ctypes.Structure):
                        _fields_ = [('dwLength', c_ulong),
                                    ('dwMemoryLoad', c_ulong),
                                    ('dwTotalPhys', c_ulonglong),
                                    ('dwAvailPhys', c_ulonglong),
                                    ('dwTotalPageFile', c_ulonglong),
                                    ('dwAvailPageFile', c_ulonglong),
                                    ('dwTotalVirtual', c_ulonglong),
                                    ('dwAvailVirtual', c_ulonglong),
                                    ('availExtendedVirtual', c_ulonglong)]

                    memoryStatus = MEMORYSTATUS()
                    memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS)
                    kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus))
                    environment['mem_total'] = str(
                        int(memoryStatus.dwTotalPhys) / (1024**2))
                    environment['mem_free'] = str(
                        int(memoryStatus.dwAvailPhys) / (1024**2))

                else:
                    with open('/proc/meminfo') as f:
                        meminfo = f.read()
                    environment['mem_total'] = str(
                        int(
                            re.search(r'MemTotal:\s+(\d+)',
                                      meminfo).groups()[0]) / 1024)
                    environment['mem_free'] = str(
                        int(
                            re.search(r'MemAvailable:\s+(\d+)',
                                      meminfo).groups()[0]) / 1024)
            except:
                environment['mem_total'] = ''
                environment['mem_free'] = ''

        try:
            environment['kodi_buffer'] = '20'
            environment['kodi_bmode'] = '0'
            environment['kodi_rfactor'] = '4.0'
            if filetools.exists(
                    filetools.join(xbmc.translatePath("special://userdata"),
                                   "advancedsettings.xml")):
                advancedsettings = filetools.read(
                    filetools.join(xbmc.translatePath("special://userdata"),
                                   "advancedsettings.xml")).split('\n')
                for label_a in advancedsettings:
                    if 'memorysize' in label_a:
                        environment['kodi_buffer'] = str(
                            int(
                                scrapertools.find_single_match(
                                    label_a, '>(\d+)<\/')) / 1024**2)
                    if 'buffermode' in label_a:
                        environment['kodi_bmode'] = str(
                            scrapertools.find_single_match(
                                label_a, '>(\d+)<\/'))
                    if 'readfactor' in label_a:
                        environment['kodi_rfactor'] = str(
                            scrapertools.find_single_match(
                                label_a, '>(.*?)<\/'))
        except:
            pass

        environment['userdata_path'] = str(
            xbmc.translatePath(config.get_data_path()))
        try:
            if environment['os_name'].lower() == 'windows':
                free_bytes = ctypes.c_ulonglong(0)
                ctypes.windll.kernel32.GetDiskFreeSpaceExW(
                    ctypes.c_wchar_p(environment['userdata_path']), None, None,
                    ctypes.pointer(free_bytes))
                environment['userdata_free'] = str(
                    round(float(free_bytes.value) / (1024**3), 3))
            else:
                disk_space = os.statvfs(environment['userdata_path'])
                if not disk_space.f_frsize:
                    disk_space.f_frsize = disk_space.f_frsize.f_bsize
                environment['userdata_free'] = str(round((float(disk_space.f_bavail) / \
                                (1024**3)) * float(disk_space.f_frsize), 3))
        except:
            environment['userdata_free'] = '?'

        try:
            environment['videolab_series'] = '?'
            environment['videolab_episodios'] = '?'
            environment['videolab_pelis'] = '?'
            environment['videolab_path'] = str(
                xbmc.translatePath(config.get_videolibrary_path()))
            if filetools.exists(filetools.join(environment['videolab_path'], \
                                config.get_setting("folder_tvshows"))):
                environment['videolab_series'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \
                                config.get_setting("folder_tvshows")))))
                counter = 0
                for root, folders, files in filetools.walk(filetools.join(environment['videolab_path'], \
                                    config.get_setting("folder_tvshows"))):
                    for file in files:
                        if file.endswith('.strm'): counter += 1
                environment['videolab_episodios'] = str(counter)
            if filetools.exists(filetools.join(environment['videolab_path'], \
                                config.get_setting("folder_movies"))):
                environment['videolab_pelis'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \
                                config.get_setting("folder_movies")))))
        except:
            pass
        try:
            video_updates = ['No', 'Inicio', 'Una vez', 'Inicio+Una vez']
            environment['videolab_update'] = str(
                video_updates[config.get_setting("update", "videolibrary")])
        except:
            environment['videolab_update'] = '?'
        try:
            if environment['os_name'].lower() == 'windows':
                free_bytes = ctypes.c_ulonglong(0)
                ctypes.windll.kernel32.GetDiskFreeSpaceExW(
                    ctypes.c_wchar_p(environment['videolab_path']), None, None,
                    ctypes.pointer(free_bytes))
                environment['videolab_free'] = str(
                    round(float(free_bytes.value) / (1024**3), 3))
            else:
                disk_space = os.statvfs(environment['videolab_path'])
                if not disk_space.f_frsize:
                    disk_space.f_frsize = disk_space.f_frsize.f_bsize
                environment['videolab_free'] = str(round((float(disk_space.f_bavail) / \
                                (1024**3)) * float(disk_space.f_frsize), 3))
        except:
            environment['videolab_free'] = '?'

        environment['torrent_list'] = []
        environment['torrentcli_option'] = ''
        environment['torrent_error'] = ''
        environment['torrentcli_rar'] = config.get_setting("mct_rar_unpack",
                                                           server="torrent",
                                                           default=True)
        environment['torrentcli_backgr'] = config.get_setting(
            "mct_background_download", server="torrent", default=True)
        environment['torrentcli_lib_path'] = config.get_setting(
            "libtorrent_path", server="torrent", default="")
        if environment['torrentcli_lib_path']:
            lib_path = 'Activo'
        else:
            lib_path = 'Inactivo'
        environment['torrentcli_unrar'] = config.get_setting("unrar_path",
                                                             server="torrent",
                                                             default="")
        if environment['torrentcli_unrar']:
            if xbmc.getCondVisibility("system.platform.Android"):
                unrar = 'Android'
            else:
                unrar, bin = filetools.split(environment['torrentcli_unrar'])
                unrar = unrar.replace('\\', '/')
                if not unrar.endswith('/'):
                    unrar = unrar + '/'
                unrar = scrapertools.find_single_match(
                    unrar, '\/([^\/]+)\/$').capitalize()
        else:
            unrar = 'Inactivo'
        torrent_id = config.get_setting("torrent_client",
                                        server="torrent",
                                        default=0)
        environment['torrentcli_option'] = str(torrent_id)
        torrent_options = platformtools.torrent_client_installed()
        if lib_path == 'Activo':
            torrent_options = ['MCT'] + torrent_options
            torrent_options = ['BT'] + torrent_options
        environment['torrent_list'].append({'Torrent_opt': str(torrent_id), 'Libtorrent': lib_path, \
                                            'RAR_Auto': str(environment['torrentcli_rar']), \
                                            'RAR_backgr': str(environment['torrentcli_backgr']), \
                                            'UnRAR': unrar})
        environment['torrent_error'] = config.get_setting("libtorrent_error",
                                                          server="torrent",
                                                          default="")
        if environment['torrent_error']:
            environment['torrent_list'].append(
                {'Libtorrent_error': environment['torrent_error']})

        for torrent_option in torrent_options:
            cliente = dict()
            cliente['D_load_Path'] = ''
            cliente['Libre'] = '?'
            cliente['Plug_in'] = torrent_option.replace('Plugin externo: ', '')
            if cliente['Plug_in'] == 'BT':
                cliente['D_load_Path'] = str(
                    config.get_setting("bt_download_path",
                                       server="torrent",
                                       default=''))
                if not cliente['D_load_Path']: continue
                cliente['Buffer'] = str(
                    config.get_setting("bt_buffer",
                                       server="torrent",
                                       default=50))
            elif cliente['Plug_in'] == 'MCT':
                cliente['D_load_Path'] = str(
                    config.get_setting("mct_download_path",
                                       server="torrent",
                                       default=''))
                if not cliente['D_load_Path']: continue
                cliente['Buffer'] = str(
                    config.get_setting("mct_buffer",
                                       server="torrent",
                                       default=50))
            elif xbmc.getCondVisibility('System.HasAddon("plugin.video.%s")' %
                                        cliente['Plug_in']):
                __settings__ = xbmcaddon.Addon(id="plugin.video.%s" %
                                               cliente['Plug_in'])
                cliente['Plug_in'] = cliente['Plug_in'].capitalize()
                if cliente['Plug_in'] == 'Torrenter':
                    cliente['D_load_Path'] = str(
                        xbmc.translatePath(__settings__.getSetting('storage')))
                    if not cliente['D_load_Path']:
                        cliente['D_load_Path'] = str(filetools.join(xbmc.translatePath("special://home/"), \
                                                     "cache", "xbmcup", "plugin.video.torrenter", "Torrenter"))
                    cliente['Buffer'] = str(
                        __settings__.getSetting('pre_buffer_bytes'))
                else:
                    cliente['D_load_Path'] = str(
                        xbmc.translatePath(
                            __settings__.getSetting('download_path')))
                    cliente['Buffer'] = str(
                        __settings__.getSetting('buffer_size'))
                    if __settings__.getSetting(
                            'download_storage'
                    ) == '1' and __settings__.getSetting('memory_size'):
                        cliente['Memoria'] = str(
                            __settings__.getSetting('memory_size'))

            if cliente['D_load_Path']:
                try:
                    if environment['os_name'].lower() == 'windows':
                        free_bytes = ctypes.c_ulonglong(0)
                        ctypes.windll.kernel32.GetDiskFreeSpaceExW(
                            ctypes.c_wchar_p(cliente['D_load_Path']), None,
                            None, ctypes.pointer(free_bytes))
                        cliente['Libre'] = str(round(float(free_bytes.value) / \
                                    (1024**3), 3)).replace('.', ',')
                    else:
                        disk_space = os.statvfs(cliente['D_load_Path'])
                        if not disk_space.f_frsize:
                            disk_space.f_frsize = disk_space.f_frsize.f_bsize
                        cliente['Libre'] = str(round((float(disk_space.f_bavail) / \
                                    (1024**3)) * float(disk_space.f_frsize), 3)).replace('.', ',')
                except:
                    pass
            environment['torrent_list'].append(cliente)

        environment['proxy_active'] = ''
        try:
            proxy_channel_bloqued_str = base64.b64decode(
                config.get_setting('proxy_channel_bloqued')).decode('utf-8')
            proxy_channel_bloqued = dict()
            proxy_channel_bloqued = ast.literal_eval(proxy_channel_bloqued_str)
            for channel_bloqued, proxy_active in proxy_channel_bloqued.items():
                if proxy_active == 'ON':
                    environment['proxy_active'] += channel_bloqued + ', '
        except:
            pass
        if not environment['proxy_active']: environment['proxy_active'] = 'OFF'
        environment['proxy_active'] = environment['proxy_active'].rstrip(', ')

        for root, folders, files in filetools.walk(
                xbmc.translatePath("special://logpath/")):
            for file in files:
                if file.lower() in ['kodi.log', 'jarvis.log', 'spmc.log', 'cemc.log', \
                                    'mygica.log', 'wonderbox.log', 'leiapp,log', \
                                    'leianmc.log', 'kodiapp.log', 'anmc.log', \
                                    'latin-anmc.log']:
                    environment['log_path'] = str(filetools.join(root, file))
                    break
            else:
                environment['log_path'] = ''
            break

        if environment['log_path']:
            environment['log_size_bytes'] = str(
                filetools.getsize(environment['log_path']))
            environment['log_size'] = str(round(float(environment['log_size_bytes']) / \
                                (1024*1024), 3))
        else:
            environment['log_size_bytes'] = ''
            environment['log_size'] = ''

        environment['debug'] = str(config.get_setting('debug'))
        environment['addon_version'] = str(config.get_addon_version())

    except:
        logger.error(traceback.format_exc())
        environment = {}
        environment['log_size'] = ''
        environment['cpu_usage'] = ''
        environment['python_version'] = ''
        environment['log_path'] = ''
        environment['userdata_free'] = ''
        environment['mem_total'] = ''
        environment['machine'] = ''
        environment['platform'] = ''
        environment['videolab_path'] = ''
        environment['num_version'] = ''
        environment['os_name'] = ''
        environment['video_db'] = ''
        environment['userdata_path'] = ''
        environment['log_size_bytes'] = ''
        environment['name_version'] = ''
        environment['language'] = ''
        environment['mem_free'] = ''
        environment['prod_model'] = ''
        environment['proxy_active'] = ''
        environment['architecture'] = ''
        environment['os_release'] = ''
        environment['videolab_free'] = ''
        environment['kodi_buffer'] = ''
        environment['kodi_bmode'] = ''
        environment['kodi_rfactor'] = ''
        environment['videolab_series'] = ''
        environment['videolab_episodios'] = ''
        environment['videolab_pelis'] = ''
        environment['videolab_update'] = ''
        environment['debug'] = ''
        environment['addon_version'] = ''
        environment['torrent_list'] = []
        environment['torrentcli_option'] = ''
        environment['torrentcli_rar'] = ''
        environment['torrentcli_lib_path'] = ''
        environment['torrentcli_unrar'] = ''
        environment['torrent_error'] = ''

    return environment
Example #16
0
    def extract(self,
                file,
                dir,
                folder_to_extract="",
                overwrite_question=False,
                backup=False):
        logger.info("file=%s" % file)
        logger.info("dir=%s" % dir)

        if not dir.endswith(':') and not filetools.exists(dir):
            filetools.mkdir(dir)

        zf = zipfile.ZipFile(file)
        if not folder_to_extract:
            self._createstructure(file, dir)
        num_files = len(zf.namelist())

        for nameo in zf.namelist():
            name = nameo.replace(':', '_').replace('<', '_').replace(
                '>',
                '_').replace('|',
                             '_').replace('"',
                                          '_').replace('?',
                                                       '_').replace('*', '_')
            logger.info("name=%s" % nameo)
            if not name.endswith('/'):
                logger.info("no es un directorio")
                try:
                    (path,
                     filename) = filetools.split(filetools.join(dir, name))
                    logger.info("path=%s" % path)
                    logger.info("name=%s" % name)
                    if folder_to_extract:
                        if path != filetools.join(dir, folder_to_extract):
                            break
                    else:
                        filetools.mkdir(path)
                except:
                    pass
                if folder_to_extract:
                    outfilename = filetools.join(dir, filename)

                else:
                    outfilename = filetools.join(dir, name)
                logger.info("outfilename=%s" % outfilename)
                try:
                    if filetools.exists(outfilename) and overwrite_question:
                        from platformcode import platformtools
                        dyesno = platformtools.dialog_yesno("El archivo ya existe",
                                                            "El archivo %s a descomprimir ya existe" \
                                                            ", ¿desea sobrescribirlo?" \
                                                            % filetools.basename(outfilename))
                        if not dyesno:
                            break
                        if backup:
                            import time
                            hora_folder = "Copia seguridad [%s]" % time.strftime(
                                "%d-%m_%H-%M", time.localtime())
                            backup = filetools.join(config.get_data_path(),
                                                    'backups', hora_folder,
                                                    folder_to_extract)
                            if not filetools.exists(backup):
                                filetools.mkdir(backup)
                            filetools.copy(
                                outfilename,
                                filetools.join(
                                    backup, filetools.basename(outfilename)))

                    outfile = filetools.file_open(outfilename, 'wb')
                    outfile.write(zf.read(nameo))
                except:
                    import traceback
                    logger.error(traceback.format_exc())
                    logger.error("Error en fichero " + nameo)

        try:
            zf.close()
        except:
            logger.info("Error cerrando .zip " + file)
Example #17
0
def mostrar_perfil(item):
    logger.info()
    alfav = AlfavoritesData()

    itemlist = []

    i_perfil = item.i_perfil
    if not alfav.user_favorites[i_perfil]: return itemlist
    last_i = len(alfav.user_favorites[i_perfil]['items']) - 1

    ruta_runtime = config.get_runtime_path()

    for i_enlace, enlace in enumerate(alfav.user_favorites[i_perfil]['items']):
        context = []

        if i_enlace > 0:
            context.append({
                'title': 'Mover arriba del todo',
                'channel': item.channel,
                'action': 'mover_enlace',
                'i_enlace': i_enlace,
                'i_perfil': i_perfil,
                'direccion': 'top'
            })
            context.append({
                'title': 'Mover hacia arriba',
                'channel': item.channel,
                'action': 'mover_enlace',
                'i_enlace': i_enlace,
                'i_perfil': i_perfil,
                'direccion': 'arriba'
            })
        if i_enlace < last_i:
            context.append({
                'title': 'Mover hacia abajo',
                'channel': item.channel,
                'action': 'mover_enlace',
                'i_enlace': i_enlace,
                'i_perfil': i_perfil,
                'direccion': 'abajo'
            })
            context.append({
                'title': 'Mover abajo del todo',
                'channel': item.channel,
                'action': 'mover_enlace',
                'i_enlace': i_enlace,
                'i_perfil': i_perfil,
                'direccion': 'bottom'
            })

        if len(
                alfav.user_favorites
        ) > 1:  # si se tiene más de una carpeta permitir mover entre ellas
            context.append({
                'title': 'Mover a otra carpeta',
                'channel': item.channel,
                'action': 'editar_enlace_carpeta',
                'i_enlace': i_enlace,
                'i_perfil': i_perfil
            })

        context.append({
            'title': 'Cambiar título',
            'channel': item.channel,
            'action': 'editar_enlace_titulo',
            'i_enlace': i_enlace,
            'i_perfil': i_perfil
        })

        context.append({
            'title': 'Cambiar color',
            'channel': item.channel,
            'action': 'editar_enlace_color',
            'i_enlace': i_enlace,
            'i_perfil': i_perfil
        })

        context.append({
            'title': 'Cambiar thumbnail',
            'channel': item.channel,
            'action': 'editar_enlace_thumbnail',
            'i_enlace': i_enlace,
            'i_perfil': i_perfil
        })

        context.append({
            'title': 'Eliminar enlace',
            'channel': item.channel,
            'action': 'eliminar_enlace',
            'i_enlace': i_enlace,
            'i_perfil': i_perfil
        })

        it = Item().fromurl(enlace)
        it.context = context
        it.plot = '[COLOR blue]Canal: ' + it.channel + '[/COLOR][CR]' + it.plot

        # Si no es una url, ni tiene la ruta del sistema, convertir el path ya que se habrá copiado de otro dispositivo.
        # Sería más óptimo que la conversión se hiciera con un menú de importar, pero de momento se controla en run-time.
        if it.thumbnail and '://' not in it.thumbnail and not it.thumbnail.startswith(
                ruta_runtime):
            ruta, fichero = filetools.split(it.thumbnail)
            if ruta == '' and fichero == it.thumbnail:  # en linux el split con un path de windows no separa correctamente
                ruta, fichero = filetools.split(it.thumbnail.replace(
                    '\\', '/'))
            if 'channels' in ruta and 'thumb' in ruta:
                it.thumbnail = filetools.join(ruta_runtime, 'resources',
                                              'media', 'channels', 'thumb',
                                              fichero)
            elif 'themes' in ruta and 'default' in ruta:
                it.thumbnail = filetools.join(ruta_runtime, 'resources',
                                              'media', 'themes', 'default',
                                              fichero)

        itemlist.append(it)

    return itemlist
Example #18
0
def extract_files(rar_file, save_path_videos, password, dp, item=None, torr_client=None):
    logger.info()
    import sys
    #reload(sys)
    #sys.setdefaultencoding('utf-8')
    sys.path.insert(0, config.get_setting("unrar_path", server="torrent", default="")\
                    .replace('/unrar', '').replace('\\unrar,exe', ''))
    
    import rarfile

    # Verificamos si hay path para UnRAR
    rarfile.UNRAR_TOOL = config.get_setting("unrar_path", server="torrent", default="")
    if not rarfile.UNRAR_TOOL:
        if xbmc.getCondVisibility("system.platform.Android"):
            rarfile.UNRAR_TOOL = xbmc.executebuiltin("StartAndroidActivity(com.rarlab.rar)")
        return rar_file, False, '', ''
    log("##### unrar_path: %s" % rarfile.UNRAR_TOOL)
    rarfile.DEFAULT_CHARSET = 'utf-8'
    
    # Preparamos un path alternativo más corto para no sobrepasar la longitud máxima
    video_path = ''
    if item:
        if item.contentType == 'movie':
            video_path = '%s-%s' % (item.contentTitle, item.infoLabels['tmdb_id'])
        else:
            video_path = '%s-%sx%s-%s' % (item.contentSerieName, item.contentSeason, \
                            item.contentEpisodeNumber, item.infoLabels['tmdb_id'])
    
    # Renombramos el path dejado en la descarga a uno más corto
    rename_status = False
    org_rar_file = rar_file
    org_save_path_videos = save_path_videos
    if video_path and '/' in rar_file:
        log("##### rar_file: %s" % rar_file)
        rename_status, rar_file = rename_rar_dir(org_rar_file, org_save_path_videos, video_path, torr_client)

    # Calculamos el path para del RAR
    if "/" in rar_file:
        folders = rar_file.split("/")
        erase_file_path = filetools.join(save_path_videos, folders[0])
        file_path = save_path_videos
        for f in folders:
            file_path = filetools.join(file_path, f)
    else:
        file_path = save_path_videos
        erase_file_path = save_path_videos

    # Calculamos el path para la extracción
    if "/" in rar_file:
        folders = rar_file.split("/")
        for f in folders:
            if not '.rar' in f:
                save_path_videos = filetools.join(save_path_videos, f)
    save_path_videos = filetools.join(save_path_videos, 'Extracted')
    if not filetools.exists(save_path_videos): filetools.mkdir(save_path_videos)
    log("##### save_path_videos: %s" % save_path_videos)

    # Permite hasta 5 pasadas de extracción de .RARs anidados
    platformtools.dialog_notification("Empezando extracción...", rar_file, time=5000)
    for x in range(5):
        try:
            archive = rarfile.RarFile(file_path.decode("utf8"))
        except:
            log("##### ERROR en Archivo rar: %s" % rar_file)
            log("##### ERROR en Carpeta del rar: %s" % file_path)
            log(traceback.format_exc())
            platformtools.dialog_notification("Error al abrir el RAR", "Comprueba el log para más detalles")
            return rar_file, False, '', ''

        # Analizamos si es necesaria una contraseña, que debería estar en item.password
        if archive.needs_password():
            if not password:
                pass_path = filetools.split(file_path)[0]
                password = last_password_search(pass_path)
            if not password :
                password = platformtools.dialog_input(heading="Introduce la contraseña (Mira en %s)" % pass_path)
                if not password:
                    return rar_file, False, '', ''
            archive.setpassword(password)
            log("##### Password rar: %s" % password)

        # Miramos el contenido del RAR a extraer
        files = archive.infolist()
        info = []
        for idx, i in enumerate(files):
            if i.file_size == 0:
                files.pop(idx)
                continue
            filename = i.filename
            if "/" in filename:
                filename = filename.rsplit("/", 1)[1]

            info.append("%s - %.2f MB" % (filename, i.file_size / 1048576.0))
        if info:
            info.append("Extraer todo sin reproducir")
        else:
            platformtools.dialog_notification("El RAR está vacío", "O no contiene archivos válidos")
            return rar_file, False, '', erase_file_path

        # Seleccionamos extraer TODOS los archivos del RAR
        #selection = xbmcgui.Dialog().select("Selecciona el fichero a extraer y reproducir", info)
        selection = len(info) - 1
        if selection < 0:
            return rar_file, False, '', erase_file_path
        else:
            try:
                log("##### RAR Extract INI #####")
                if selection == len(info) - 1:
                    log("##### rar_file 1: %s" % file_path)
                    log("##### save_path_videos 1: %s" % save_path_videos)
                    dp.update(99, "Extrayendo archivos...", "Espera unos minutos....")
                    archive.extractall(save_path_videos)
                else:
                    log("##### rar_file 2: %s" % file_path)
                    log("##### save_path_videos 2: %s" % save_path_videos)
                    dp.update(99, "Espera unos minutos....", "Extrayendo archivo... %s" % info[selection])
                    archive.extract(files[selection], save_path_videos)
                log("##### RAR Extract END #####")
            except (rarfile.RarWrongPassword, rarfile.RarCRCError):
                platformtools.dialog_notification("Error al extraer", "Contraseña incorrecta")
                log(traceback.format_exc(1))
                return rar_file, False, '', erase_file_path
            except rarfile.BadRarFile:
                platformtools.dialog_notification("Error al extraer", "Archivo rar con errores")
                log(traceback.format_exc(1))
                return rar_file, False, '', erase_file_path
            except:
                platformtools.dialog_notification("Error al extraer", "Comprueba el log para más detalles")
                log(traceback.format_exc(1))
                return rar_file, False, '', erase_file_path

            extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg',
                               '.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg',
                               '.mpe', '.mp4', '.ogg', '.wmv']
            
            # Localizamos el path donde se ha dejado la extracción
            folder = True
            file_result = filetools.listdir(save_path_videos)
            while folder:
                for file_r in file_result:
                    if filetools.isdir(filetools.join(save_path_videos, file_r)):
                        file_result_alt = filetools.listdir(filetools.join(save_path_videos, file_r))
                        if file_result_alt:
                            file_result = file_result_alt
                            save_path_videos = filetools.join(save_path_videos, file_r)
                        else:
                            folder = False
                        break
                else:
                    folder = False

            # Si hay RARs anidados, ajustamos los paths para la siguiente pasada
            if '.rar' in str(file_result):
                for file_r in file_result:
                    if '.rar' in file_r:
                        rar_file = file_r
                        file_path = str(filetools.join(save_path_videos, rar_file))
                        save_path_videos = filetools.join(save_path_videos, 'Extracted')
                        if not filetools.exists(save_path_videos): filetools.mkdir(save_path_videos)
                        platformtools.dialog_notification("Siguiente extracción...", rar_file, time=5000)
            
            # Si ya se ha extraido todo, preparamos el retorno            
            else:
                video_list = []
                for file_r in file_result:
                    if os.path.splitext(file_r)[1] in extensions_list:
                        video_list += [file_r]
                if len(video_list) == 0:
                    platformtools.dialog_notification("El rar está vacío", "O no contiene archivos válidos")
                    return rar_file, False, '', erase_file_path
                else:
                    log("##### Archivo extraído: %s" % video_list[0])
                    platformtools.dialog_notification("Archivo extraído...", video_list[0], time=10000)
                    return str(video_list[0]), True, save_path_videos, erase_file_path
Example #19
0
def get_results(nfo_path, root, Type, local=False):
    value = 0
    if Type == 'movie': folder = "folder_movies"
    else: folder = "folder_tvshows"

    if filetools.exists(nfo_path):
        # We synchronize the episodes seen from the Kodi video library with that of KoD
        from platformcode import xbmc_videolibrary
        xbmc_videolibrary.mark_content_as_watched_on_kod(nfo_path)
        head_nfo, item = videolibrarytools.read_nfo(nfo_path)

        # If you have not read the .nfo well, we will proceed to the next
        if not item:
            logger.error('.nfo erroneous in ' + str(nfo_path))
            return Item(), 0

        if len(item.library_urls) > 1: multichannel = True
        else: multichannel = False

        # continue loading the elements of the video library
        if Type == 'movie':
            item.path = filetools.split(nfo_path)[0]
            item.nfo = nfo_path
            sep = '/' if '/' in nfo_path else '\\'
            item.extra = filetools.join(config.get_setting("videolibrarypath"), config.get_setting(folder), item.path.split(sep)[-1])
            strm_path = item.strm_path.replace("\\", "/").rstrip("/")
            if not item.thumbnail: item.thumbnail = item.infoLabels['thumbnail']
            if '/' in item.path: item.strm_path = strm_path
            # If strm has been removed from kodi library, don't show it
            if not filetools.exists(filetools.join(item.path, filetools.basename(strm_path))) and not local: return Item(), 0

            # Contextual menu: Mark as seen / not seen
            visto = item.library_playcounts.get(item.path.split(sep)[0], 0)
            item.infoLabels["playcount"] = visto
            if visto > 0:
                seen_text = config.get_localized_string(60016)
                counter = 0
            else:
                seen_text = config.get_localized_string(60017)
                counter = 1

            # Context menu: Delete series / channel
            channels_num = len(item.library_urls)
            if "downloads" in item.library_urls: channels_num -= 1
            if channels_num > 1: delete_text = config.get_localized_string(60018)
            else: delete_text = config.get_localized_string(60019)

            item.context = [{"title": seen_text, "action": "mark_content_as_watched", "channel": "videolibrary",  "playcount": counter},
                            {"title": delete_text, "action": "delete", "channel": "videolibrary", "multichannel": multichannel}]
        else:
            # Sometimes it gives random errors, for not finding the .nfo. Probably timing issues
            try:
                item.title = item.contentTitle
                item.path = filetools.split(nfo_path)[0]
                item.nfo = nfo_path
                sep = '/' if '/' in nfo_path else '\\'
                item.extra = filetools.join(config.get_setting("videolibrarypath"), config.get_setting(folder), item.path.split(sep)[-1])
                # Contextual menu: Mark as seen / not seen
                visto = item.library_playcounts.get(item.contentTitle, 0)
                item.infoLabels["playcount"] = visto
                logger.debug('item\n' + str(item))
                if visto > 0:
                    seen_text = config.get_localized_string(60020)
                    counter = 0
                else:
                    seen_text = config.get_localized_string(60021)
                    counter = 1

            except:
                logger.error('Not find: ' + str(nfo_path))
                logger.error(traceback.format_exc())
                return Item(), 0

            # Context menu: Automatically search for new episodes or not
            if item.active and int(item.active) > 0:
                update_text = config.get_localized_string(60022)
                value = 0
            else:
                update_text = config.get_localized_string(60023)
                value = 1
                item.title += " [B]" + u"\u2022" + "[/B]"

            # Context menu: Delete series / channel
            channels_num = len(item.library_urls)
            if "downloads" in item.library_urls: channels_num -= 1
            if channels_num > 1: delete_text = config.get_localized_string(60024)
            else: delete_text = config.get_localized_string(60025)

            item.context = [{"title": seen_text, "action": "mark_content_as_watched", "channel": "videolibrary", "playcount": counter},
                            {"title": update_text, "action": "mark_tvshow_as_updatable", "channel": "videolibrary", "active": value},
                            {"title": delete_text, "action": "delete", "channel": "videolibrary", "multichannel": multichannel},
                            {"title": config.get_localized_string(70269), "action": "update_tvshow", "channel": "videolibrary"}]
            if item.local_episodes_path == "": item.context.append({"title": config.get_localized_string(80048), "action": "add_local_episodes", "channel": "videolibrary"})
            else: item.context.append({"title": config.get_localized_string(80049), "action": "remove_local_episodes", "channel": "videolibrary"})
    else: item = Item()
    return item, value
Example #20
0
def move_to_libray(item):
    if item.contentType == 'movie':
        FOLDER = FOLDER_MOVIES
        path_title = "%s [%s]" % (item.contentTitle.strip(),
                                  item.infoLabels['IMDBNumber'])
        move_path = filetools.join(config.get_videolibrary_path(), FOLDER,
                                   path_title)

    else:
        FOLDER = FOLDER_TVSHOWS
        path_title = "%s [%s]" % (item.contentSerieName,
                                  item.infoLabels['IMDBNumber'])
        move_path = filetools.join(config.get_videolibrary_path(), FOLDER)

    download_path = filetools.join(config.get_setting("downloadpath"),
                                   item.downloadFilename)
    library_path = filetools.join(move_path,
                                  *filetools.split(item.downloadFilename))
    final_path = download_path

    if config.get_setting("library_add",
                          "downloads") == True and config.get_setting(
                              "library_move", "downloads") == 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))

        logger.info('ITEM = ' + str(item))
        name = item.contentTitle if item.contentType == 'movie' else str(
            item.infoLabels['season']) + 'x' + str(
                item.infoLabels['episode']).zfill(2)
        list_item = os.listdir(
            filetools.join(config.get_videolibrary_path(), FOLDER, path_title))

        clean = False
        for File in list_item:
            filename = File.lower()
            name = name.lower()
            if filename.startswith(name) and (filename.endswith('.strm')
                                              or filename.endswith('.json')
                                              or filename.endswith('.nfo')):
                clean = True
                logger.info('Delete File: ' + str(
                    os.path.join(config.get_videolibrary_path(), FOLDER,
                                 path_title, File)))
                os.remove(
                    os.path.join(config.get_videolibrary_path(), FOLDER,
                                 path_title, File))
        from platformcode import xbmc_videolibrary

        xbmc_videolibrary.update(FOLDER)
        if clean == True:
            import xbmc
            while xbmc.getCondVisibility('Library.IsScanningVideo()'):
                xbmc.sleep(500)
            xbmc_videolibrary.clean()

    if config.get_setting("library_add",
                          "downloads") == True and config.get_setting(
                              "library_move", "downloads") == False:
        if filetools.isfile(final_path):
            if item.contentType == "movie" and item.infoLabels["tmdb_id"]:
                library_item = Item(title=config.get_localized_string(70228) %
                                    item.downloadFilename,
                                    channel="downloads",
                                    action="findvideos",
                                    infoLabels=item.infoLabels,
                                    url=final_path)
                videolibrarytools.save_movie(library_item)

            elif item.contentType == "episode" and item.infoLabels["tmdb_id"]:
                library_item = Item(title=config.get_localized_string(70228) %
                                    item.downloadFilename,
                                    channel="downloads",
                                    action="findvideos",
                                    infoLabels=item.infoLabels,
                                    url=final_path)
                tvshow = Item(
                    channel="downloads",
                    contentType="tvshow",
                    infoLabels={"tmdb_id": item.infoLabels["tmdb_id"]})
                videolibrarytools.save_tvshow(tvshow, [library_item])
Example #21
0
 def create_necessary_paths(filename):
     try:
         (path, name) = filetools.split(filename)
         filetools.mkdir(path)
     except:
         pass
Example #22
0
def mark_content_as_watched_on_kodi(item, value=1):
    """
    marca el contenido como visto o no visto 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'))
    payload_f = ''

    if item.contentType == "movie":
        movieid = 0
        payload = {"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies",
                   "params": {"properties": ["title", "playcount", "originaltitle", "file"]},
                   "id": 1}

        data = get_data(payload)
        if 'result' in data and "movies" in data['result']:

            if item.strm_path:              #Si Item es de un episodio
                filename = filetools.basename(item.strm_path)
                head, tail = filetools.split(filetools.split(item.strm_path)[0])
            else:                           #Si Item es de la Serie
                filename = filetools.basename(item.path)
                head, tail = filetools.split(filetools.split(item.path)[0])
            path = filetools.join(tail, filename)

            for d in data['result']['movies']:
                if d['file'].replace("/", "\\").endswith(path.replace("/", "\\")):
                    # logger.debug("marco la pelicula como vista")
                    movieid = d['movieid']
                    break

        if movieid != 0:
            payload_f = {"jsonrpc": "2.0", "method": "VideoLibrary.SetMovieDetails", "params": {
                "movieid": movieid, "playcount": value}, "id": 1}

    else:  # item.contentType != 'movie'
        episodeid = 0
        payload = {"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes",
                   "params": {"properties": ["title", "playcount", "showtitle", "file", "tvshowid"]},
                   "id": 1}

        data = get_data(payload)
        if 'result' in data and "episodes" in data['result']:

            if item.strm_path:              #Si Item es de un episodio
                filename = filetools.basename(item.strm_path)
                head, tail = filetools.split(filetools.split(item.strm_path)[0])
            else:                           #Si Item es de la Serie
                filename = filetools.basename(item.path)
                head, tail = filetools.split(filetools.split(item.path)[0])
            path = filetools.join(tail, filename)

            for d in data['result']['episodes']:

                if d['file'].replace("/", "\\").endswith(path.replace("/", "\\")):
                    # logger.debug("marco el episodio como visto")
                    episodeid = d['episodeid']
                    break

        if episodeid != 0:
            payload_f = {"jsonrpc": "2.0", "method": "VideoLibrary.SetEpisodeDetails", "params": {
                "episodeid": episodeid, "playcount": value}, "id": 1}

    if payload_f:
        # Marcar como visto
        data = get_data(payload_f)
        # logger.debug(str(data))
        if data['result'] != 'OK':
            logger.error("ERROR al poner el contenido como visto")
Example #23
0
def downloadpage(url, **opt):
    logger.info()



    """
        Abre una url y retorna los datos obtenidos

        @param url: url que abrir.
        @type url: str
        @param post: Si contiene algun valor este es enviado mediante POST.
        @type post: str
        @param headers: Headers para la petición, si no contiene nada se usara los headers por defecto.
        @type headers: dict, list
        @param timeout: Timeout para la petición.
        @type timeout: int
        @param follow_redirects: Indica si se han de seguir las redirecciones.
        @type follow_redirects: bool
        @param cookies: Indica si se han de usar las cookies.
        @type cookies: bool
        @param replace_headers: Si True, los headers pasados por el parametro "headers" sustituiran por completo los headers por defecto.
                                Si False, los headers pasados por el parametro "headers" modificaran los headers por defecto.
        @type replace_headers: bool
        @param add_referer: Indica si se ha de añadir el header "Referer" usando el dominio de la url como valor.
        @type add_referer: bool
        @param only_headers: Si True, solo se descargarán los headers, omitiendo el contenido de la url.
        @type only_headers: bool
        @param random_headers: Si True, utiliza el método de seleccionar headers aleatorios.
        @type random_headers: bool
        @param ignore_response_code: Si es True, ignora el método para WebErrorException para error como el error 404 en veseriesonline, pero es un data funcional
        @type ignore_response_code: bool
        @return: Resultado de la petición
        @rtype: HTTPResponse

                Parametro               Tipo    Descripción
                ----------------------------------------------------------------------------------------------------------------
                HTTPResponse.sucess:    bool   True: Peticion realizada correctamente | False: Error al realizar la petición
                HTTPResponse.code:      int    Código de respuesta del servidor o código de error en caso de producirse un error
                HTTPResponse.error:     str    Descripción del error en caso de producirse un error
                HTTPResponse.headers:   dict   Diccionario con los headers de respuesta del servidor
                HTTPResponse.data:      str    Respuesta obtenida del servidor
                HTTPResponse.json:      dict    Respuesta obtenida del servidor en formato json
                HTTPResponse.time:      float  Tiempo empleado para realizar la petición

        """
    load_cookies()

    # Headers por defecto, si no se especifica nada
    req_headers = default_headers.copy()

    # Headers pasados como parametros
    if opt.get('headers', None) is not None:
        if not opt.get('replace_headers', False):
            req_headers.update(dict(opt['headers']))
        else:
            req_headers = dict(opt('headers'))

    if opt.get('random_headers', False) or HTTPTOOLS_DEFAULT_RANDOM_HEADERS:
        req_headers['User-Agent'] = random_useragent()
    url = urllib.quote(url, safe="%/:=&?~#+!$,;'@()*[]")

    opt['proxy_retries_counter'] = 0
    opt['url_save'] = url
    opt['post_save'] = opt.get('post', None)

    while opt['proxy_retries_counter'] <= opt.get('proxy_retries', 1):
        response = {}
        info_dict = []
        payload = dict()
        files = {}
        file_name = ''
        opt['proxy_retries_counter'] += 1
        
        session = cloudscraper.create_scraper()
        session.verify = False
        if opt.get('cookies', True):
            session.cookies = cj
        session.headers.update(req_headers)
        
        # Prepara la url en caso de necesitar proxy, o si se envía "proxies" desde el canal
        url, proxy_data, opt = check_proxy(url, **opt)
        if opt.get('proxies', None) is not None:
            session.proxies = opt['proxies']
        elif proxy_data.get('dict', {}):
            session.proxies = proxy_data['dict']
            
        inicio = time.time()
        
        if opt.get('timeout', None) is None and HTTPTOOLS_DEFAULT_DOWNLOAD_TIMEOUT is not None: 
            opt['timeout'] = HTTPTOOLS_DEFAULT_DOWNLOAD_TIMEOUT
        if opt['timeout'] == 0: opt['timeout'] = None

        if len(url) > 0:
            try:
                if opt.get('post', None) is not None or opt.get('file', None) is not None:
                    if opt.get('post', None) is not None:
                        ### Convert string post in dict
                        try:
                            json.loads(opt['post'])
                            payload = opt['post']
                        except:
                            if not isinstance(opt['post'], dict):
                                post = urlparse.parse_qs(opt['post'], keep_blank_values=1)
                                payload = dict()

                                for key, value in post.items():
                                    try:
                                        payload[key] = value[0]
                                    except:
                                        payload[key] = ''
                            else:
                                payload = opt['post']

                    ### Verifies 'file' and 'file_name' options to upload a file o buffer
                    if opt.get('file', None) is not None:
                        from core import filetools
                        if filetools.isfile(opt['file']):
                            if opt.get('file_name', None) is None:
                                path_file, opt['file_name'] = filetools.split(opt['file'])
                            files = {'file': (opt['file_name'], open(opt['file'], 'rb'))}
                            file_name = opt['file']
                        else:
                            files = {'file': (opt.get('file_name', 'Default'), opt['file'])}
                            file_name = opt.get('file_name', 'Default') + ', Buffer de memoria'
                    
                    info_dict = fill_fields_pre(url, opt, proxy_data, file_name)
                    if opt.get('only_headers', False):
                        ### Makes the request with HEAD method
                        req = session.head(url, allow_redirects=opt.get('follow_redirects', True),
                                          timeout=opt['timeout'])
                    else:
                        ### Makes the request with POST method
                        req = session.post(url, data=payload, allow_redirects=opt.get('follow_redirects', True),
                                          files=files, timeout=opt['timeout'])
                
                elif opt.get('only_headers', False):
                    info_dict = fill_fields_pre(url, opt, proxy_data, file_name)
                    ### Makes the request with HEAD method
                    req = session.head(url, allow_redirects=opt.get('follow_redirects', True),
                                      timeout=opt['timeout'])
                else:
                    info_dict = fill_fields_pre(url, opt, proxy_data, file_name)
                    ### Makes the request with GET method
                    req = session.get(url, allow_redirects=opt.get('follow_redirects', True),
                                      timeout=opt['timeout'])

            except Exception, e:
                if not opt.get('ignore_response_code', False) and not proxy_data.get('stat', ''):
                    req = requests.Response()
                    response['data'] = ''
                    response['sucess'] = False
                    info_dict.append(('Success', 'False'))
                    response['code'] = str(e)
                    info_dict.append(('Response code', str(e)))
                    info_dict.append(('Finalizado en', time.time() - inicio))
                    if not opt.get('alfa_s', False):
                        show_infobox(info_dict)
                    return type('HTTPResponse', (), response)
                else:
                    req = requests.Response()
                    req.status_code = str(e)
        
        else:
            response['data'] = ''
            response['sucess'] = False
            response['code'] = ''
            return type('HTTPResponse', (), response)
        
        response_code = req.status_code

        response['data'] = req.content
        response['url'] = req.url
        if not response['data']:
            response['data'] = ''
        try:
            response['json'] = to_utf8(req.json())
        except:
            response['json'] = dict()
        response['code'] = response_code
        response['headers'] = req.headers
        
        info_dict, response = fill_fields_post(info_dict, req, response, req_headers, inicio)

        if opt.get('cookies', True):
            save_cookies(alfa_s=opt.get('alfa_s', False))

        is_channel = inspect.getmodule(inspect.currentframe().f_back)
        is_channel = scrapertools.find_single_match(str(is_channel), "<module '(channels).*?'")
        if is_channel and isinstance(response_code, int):
            if not opt.get('ignore_response_code', False) and not proxy_data.get('stat', ''):
                if response_code > 399:
                    show_infobox(info_dict)
                    raise WebErrorException(urlparse.urlparse(url)[1])

        if not 'api.themoviedb' in url and not opt.get('alfa_s', False):
            show_infobox(info_dict)

        # Si hay error del proxy, refresca la lista y reintenta el numero indicada en proxy_retries
        response['data'], response['sucess'], url, opt = proxy_post_processing(url, proxy_data, response, opt)
        if opt.get('out_break', False):
            break