コード例 #1
0
def get_channel_json(channel_name):
    # logger.info("channel_name=" + channel_name)
    import filetools
    channel_json = None
    try:
        channel_path = filetools.join(config.get_runtime_path(), "channels",
                                      channel_name + ".json")
        if not os.path.isfile(channel_path):
            channel_path = filetools.join(config.get_runtime_path(),
                                          'channels', "p**n",
                                          channel_name + ".json")
            if not os.path.isfile(channel_path):
                channel_path = filetools.join(config.get_runtime_path(),
                                              "specials",
                                              channel_name + ".json")
                if not os.path.isfile(channel_path):
                    channel_path = filetools.join(config.get_runtime_path(),
                                                  "servers",
                                                  channel_name + ".json")
                    if not os.path.isfile(channel_path):
                        channel_path = filetools.join(
                            config.get_runtime_path(), "servers", "debriders",
                            channel_name + ".json")

        if filetools.isfile(channel_path):
            # logger.info("channel_data=" + channel_path)
            channel_json = jsontools.load(filetools.read(channel_path))
            # logger.info("channel_json= %s" % channel_json)

    except Exception, ex:
        template = "An exception of type %s occured. Arguments:\n%r"
        message = template % (type(ex).__name__, ex.args)
        logger.error(" %s" % message)
コード例 #2
0
ファイル: servertools.py プロジェクト: lozioangie/addon
def get_server_parameters(server):
    """
    Obtiene los datos del servidor
    @param server: Nombre del servidor
    @type server: str

    @return: datos del servidor
    @rtype: dict
    """
    # logger.info("server %s" % server)
    global dict_servers_parameters
    server = server.split('.')[0]
    if not server:
        return {}

    if server not in dict_servers_parameters:
        try:
            # Servers
            if os.path.isfile(os.path.join(config.get_runtime_path(), "servers", server + ".json")):
                path = os.path.join(config.get_runtime_path(), "servers", server + ".json")

            # Debriders
            elif os.path.isfile(os.path.join(config.get_runtime_path(), "servers", "debriders", server + ".json")):
                path = os.path.join(config.get_runtime_path(), "servers", "debriders", server + ".json")
            #
            #Cuando no está bien definido el server en el canal (no existe conector), muestra error por no haber "path" y se tiene que revisar el canal
            #
            data = filetools.read(path)
            dict_server = jsontools.load(data)

            # Imagenes: se admiten url y archivos locales dentro de "resources/images"
            if dict_server.get("thumbnail") and "://" not in dict_server["thumbnail"]:
                dict_server["thumbnail"] = os.path.join(config.get_runtime_path(), "resources", "media",
                                                        "servers", dict_server["thumbnail"])
            for k in ['premium', 'id']:
                dict_server[k] = dict_server.get(k, list())

                if type(dict_server[k]) == str:
                    dict_server[k] = [dict_server[k]]

            if "find_videos" in dict_server:
                dict_server['find_videos']["patterns"] = dict_server['find_videos'].get("patterns", list())
                dict_server['find_videos']["ignore_urls"] = dict_server['find_videos'].get("ignore_urls", list())

            if "settings" in dict_server:
                dict_server['has_settings'] = True
            else:
                dict_server['has_settings'] = False

            dict_servers_parameters[server] = dict_server

        except:
            mensaje = config.get_localized_string(59986) % server
            import traceback
            logger.error(mensaje + traceback.format_exc())
            return {}

    return dict_servers_parameters[server]
コード例 #3
0
def test_poly_phase(el_q, run_s):
    print(f'TESTING POLY PHASE SORT: el_q={el_q}, run_s={run_s}')

    test_file = 'test_files/test.bin'
    ftools.generate_test_file(test_file, el_q)
    res_file = poly_phase_sort(test_file, run_s)
    sort_el, start_el = [], []
    with open(test_file, 'rb') as test:
        num = ftools.read(test)
        while num is not None:
            start_el.append(num)
            num = ftools.read(test)

    with open(res_file, 'rb') as res:
        num = ftools.read(res)
        while num is not None:
            sort_el.append(num)
            num = ftools.read(res)

    os.remove(test_file)
    os.remove(res_file)

    print('OK' if sorted(start_el) == sort_el else 'FAILED')
コード例 #4
0
ファイル: channeltools.py プロジェクト: llaurator/addon
def get_channel_json(channel_name):
    # logger.info("channel_name=" + channel_name)
    import filetools
    try:
        channel_path = filetools.join(config.get_runtime_path(), "channels",
                                      channel_name + ".json")
        # logger.info("channel_data=" + channel_path)
        channel_json = jsontools.load(filetools.read(channel_path))
        # logger.info("channel_json= %s" % channel_json)

    except Exception, ex:
        template = "An exception of type %s occured. Arguments:\n%r"
        message = template % (type(ex).__name__, ex.args)
        logger.error(" %s" % message)
        channel_json = None
コード例 #5
0
def get_server_parameters(server):
    """
    Obtiene los datos del servidor
    @param server: Nombre del servidor
    @type server: str

    @return: datos del servidor
    @rtype: dict
    """
    global dict_servers_parameters
    if server not in dict_servers_parameters:
        try:
            if server == 'desconocido':
                dict_server = {
                    'active': False,
                    'id': 'desconocido',
                    'name': 'Desconocido'
                }
                dict_servers_parameters[server] = dict_server
                return dict_server

            path = os.path.join(config.get_runtime_path(), 'servers',
                                server + '.json')
            if not os.path.isfile(path):
                logger.info('No se encuentra el json del servidor: %s' %
                            server)
                return {}

            data = filetools.read(path)
            dict_server = jsontools.load(data)

            # valores por defecto si no existen:
            dict_server['active'] = dict_server.get('active', False)
            if 'find_videos' in dict_server:
                dict_server['find_videos']['patterns'] = dict_server[
                    'find_videos'].get('patterns', list())
                dict_server['find_videos']['ignore_urls'] = dict_server[
                    'find_videos'].get('ignore_urls', list())

            dict_servers_parameters[server] = dict_server

        except:
            mensaje = "Error al cargar el json del servidor: %s\n" % server
            import traceback
            logger.error(mensaje + traceback.format_exc())
            return {}

    return dict_servers_parameters[server]
コード例 #6
0
ファイル: servertools.py プロジェクト: lozioangie/addon
def get_server_json(server_name):
    # logger.info("server_name=" + server_name)
    try:
        server_path = filetools.join(config.get_runtime_path(), "servers", server_name + ".json")
        if not filetools.exists(server_path):
            server_path = filetools.join(config.get_runtime_path(), "servers", "debriders", server_name + ".json")

        # logger.info("server_path=" + server_path)
        server_json = jsontools.load(filetools.read(server_path))
        # logger.info("server_json= %s" % server_json)

    except Exception, ex:
        template = "An exception of type %s occured. Arguments:\n%r"
        message = template % (type(ex).__name__, ex.args)
        logger.error(" %s" % message)
        server_json = None
コード例 #7
0
ファイル: servertools.py プロジェクト: llaurator/addon
def get_server_parameters(server):
    """
    Obtiene los datos del servidor
    @param server: Nombre del servidor
    @type server: str

    @return: datos del servidor
    @rtype: dict
    """
    # logger.info("server %s" % server)
    global dict_servers_parameters
    server = server.split('.')[0]
    if not server:
        return {}

    if server not in dict_servers_parameters:
        try:
            # Servers
            if os.path.isfile(os.path.join(config.get_runtime_path(), "servers", server + ".json")):
                path = os.path.join(config.get_runtime_path(), "servers", server + ".json")

            # Debriders
            elif os.path.isfile(os.path.join(config.get_runtime_path(), "servers", "debriders", server + ".json")):
                path = os.path.join(config.get_runtime_path(), "servers", "debriders", server + ".json")

            import filetools
            data = filetools.read(path)
            dict_server = jsontools.load(data)

            # Imagenes: se admiten url y archivos locales dentro de "resources/images"
            if dict_server.get("thumbnail") and "://" not in dict_server["thumbnail"]:
                dict_server["thumbnail"] = os.path.join(config.get_runtime_path(), "resources", "media",
                                                        "servers", dict_server["thumbnail"])
            for k in ['premium', 'id']:
                dict_server[k] = dict_server.get(k, list())

                if type(dict_server[k]) == str:
                    dict_server[k] = [dict_server[k]]

                    # if not dict_server.has_key(k) or dict_server[k] == "":
                    #     dict_server[k] = []
                    # elif type(dict_server[k]) == dict:
                    #     dict_server[k] = dict_server[k]["value"]
                    # if type(dict_server[k]) == str:
                    #     dict_server[k] = [dict_server[k]]

            if "find_videos" in dict_server:
                dict_server['find_videos']["patterns"] = dict_server['find_videos'].get("patterns", list())
                dict_server['find_videos']["ignore_urls"] = dict_server['find_videos'].get("ignore_urls", list())

            if "settings" in dict_server:
                dict_server['has_settings'] = True
            else:
                dict_server['has_settings'] = False

            dict_servers_parameters[server] = dict_server

        except:
            mensaje = "Error al cargar el servidor: %s\n" % server
            import traceback
            logger.error(mensaje + traceback.format_exc())
            return {}

    return dict_servers_parameters[server]
コード例 #8
0
def get_default_settings(channel_name):
    import filetools, inspect

    # Check if it is a real channel
    try:
        channel = __import__('channels.%s' % channel_name,
                             fromlist=["channels.%s" % channel_name])
    except:
        return get_channel_json(channel_name).get('settings', list())

    list_language = get_lang(channel_name)

    # Check if the automatic renumbering function exists
    renumber = False
    if 'episodios' in dir(channel):
        from core import scrapertoolsV2
        if scrapertoolsV2.find_single_match(inspect.getsource(channel), r'(anime\s*=\s*True)') \
            or scrapertoolsV2.find_single_match(inspect.getsource(channel), r'(autorenumber\()'):
            renumber = True

    #  Collects configurations
    channel_language = categories = get_channel_json(channel_name).get(
        'language', list())
    channel_controls = get_channel_json(channel_name).get('settings', list())
    default_path = filetools.join(config.get_runtime_path(),
                                  'default_channel_settings' + '.json')
    default_controls = jsontools.load(filetools.read(default_path)).get(
        'settings', list())
    default_controls_renumber = jsontools.load(
        filetools.read(default_path)).get('renumber', list())
    categories = get_channel_json(channel_name).get('categories', list())

    # Apply default configurations if they do not exist
    for control in default_controls:
        if control['id'] not in str(channel_controls):
            if 'include_in_newest' in control['id']:
                label = control['id'].split('_')
                label = label[-1]
                if label == 'peliculas':
                    if 'movie' in categories:
                        control['label'] = config.get_localized_string(
                            70727) + ' - ' + config.get_localized_string(30122)
                        channel_controls.append(control)
                    else:
                        pass
                elif label == 'series':
                    if 'tvshow' in categories:
                        control['label'] = config.get_localized_string(
                            70727) + ' - ' + config.get_localized_string(30123)
                        channel_controls.append(control)
                    else:
                        pass
                elif label == 'anime':
                    if 'anime' in categories:
                        control['label'] = config.get_localized_string(
                            70727) + ' - ' + config.get_localized_string(30124)
                        channel_controls.append(control)
                    else:
                        pass

                else:
                    control['label'] = config.get_localized_string(
                        70727) + ' - ' + label.capitalize()
                    channel_controls.append(control)

            elif control['id'] == 'filter_languages':
                if len(channel_language) > 1:
                    control['lvalues'] = list_language
                    channel_controls.append(control)
                else:
                    pass

            else:
                channel_controls.append(control)

    if renumber:
        for control in default_controls_renumber:
            if control['id'] not in str(channel_controls):
                channel_controls.append(control)
            else:
                pass
    return channel_controls
コード例 #9
0
def poly_phase_sort(filename: str, s: 'int > 0'):
    if s <= 0:
        raise ValueError('Non-positive size number was passed')

    part1_start = time.time()

    temp_files_dir = str(uuid.uuid4().hex)

    part1_end = time.time()

    print('Generated temp dir and calculated distribution:',
          part1_end - part1_start, 's')
    with ftools.create_temp_files(temp_files_dir,
                                  4) as [a, b, c, d], open(filename,
                                                           'rb+') as f:
        number_of_blocks = divide_input_file(f, a, b, s)

        part2_end = time.time()
        print('Generated tmp files and filled them:', part2_end - part1_end,
              's')

        input1, input2, cur_out = a, b, c
        size, block_count = s, 0

        while block_count < number_of_blocks:
            input1.seek(0)
            input2.seek(0)

            if input1 is a:
                ftools.clear(c, d)
            else:
                ftools.clear(a, b)

            count_read = 0

            while count_read < number_of_blocks:

                block1, block2 = ftools.read(input1), ftools.read(input2)
                i, j = 0 if block1 is None else 1, 0 if block2 is None else 1

                while (i <= size or j <= size) and (block1 is not None
                                                    or block2 is not None):
                    if block1 is not None and (block2 is None
                                               or block1 < block2):
                        ftools.write(cur_out, block1)
                        if i + 1 <= size:
                            block1 = ftools.read(input1)
                            i += 0 if block1 is None else 1
                        else:
                            block1 = None
                    elif block2 is not None:
                        ftools.write(cur_out, block2)
                        if j + 1 <= size:
                            block2 = ftools.read(input2)
                            j += 0 if block2 is None else 1
                        else:
                            block2 = None

                block_count = i + j
                count_read += block_count

                if cur_out is a:
                    cur_out = b
                elif cur_out is b:
                    cur_out = a
                elif cur_out is c:
                    cur_out = d
                elif cur_out is d:
                    cur_out = c

            size *= 2
            if input1 is a:
                input1, input2, cur_out = c, d, a
            else:
                input1, input2, cur_out = a, b, c

        part3_end = time.time()
        print('Sorted all elements:', part3_end - part2_end, 's')

        cur_out = a if cur_out is c else c
        cur_out.seek(0)
        res_file = str(uuid.uuid4().hex) + '.bin'
        with open(res_file, 'wb') as res:
            block = ftools.read(cur_out)
            while block is not None:
                ftools.write(res, block)
                block = ftools.read(cur_out)
        ftools.clear(a, b, c, d)

        part4_end = time.time()
        print('Written to res file:', part4_end - part3_end, 's')
        print('Total:', part4_end - part1_end, 's')

        return res_file
コード例 #10
0
ファイル: channeltools.py プロジェクト: iz8mbw/addon
def get_default_settings(channel_name):
    import filetools
    default_path = filetools.join(config.get_runtime_path(),
                                  'default_channel_settings' + '.json')
    default_file = jsontools.load(filetools.read(default_path))

    channel_path = filetools.join(config.get_runtime_path(), 'channels',
                                  channel_name + '.json')
    adult_path = filetools.join(config.get_runtime_path(), 'channels', 'p**n',
                                channel_name + '.json')

    # from core.support import dbg; dbg()
    if os.path.exists(channel_path) or os.path.exists(adult_path):
        default_controls = default_file['settings']
        default_controls_renumber = default_file['renumber']
        channel_json = get_channel_json(channel_name)

        #  Collects configurations
        channel_language = channel_json['language']
        channel_controls = channel_json['settings']
        categories = channel_json['categories']
        not_active = channel_json['not_active'] if channel_json.has_key(
            'not_active') else []
        default_off = channel_json['default_off'] if channel_json.has_key(
            'default_off') else []

        # Apply default configurations if they do not exist
        for control in default_controls:
            if control['id'] not in str(channel_controls):
                if 'include_in_newest' in control[
                        'id'] and 'include_in_newest' not in not_active and control[
                            'id'] not in not_active:
                    label = control['id'].split('_')
                    label = label[-1]
                    if label == 'peliculas':
                        if 'movie' in categories:
                            control['label'] = config.get_localized_string(
                                70727) + ' - ' + config.get_localized_string(
                                    30122)
                            control['default'] = False if (
                                'include_in_newest' in default_off) or (
                                    'include_in_newest_peliculas'
                                    in default_off) else True
                            channel_controls.append(control)
                        else:
                            pass
                    elif label == 'series':
                        if 'tvshow' in categories:
                            control['label'] = config.get_localized_string(
                                70727) + ' - ' + config.get_localized_string(
                                    30123)
                            control['default'] = False if (
                                'include_in_newest'
                                in default_off) or ('include_in_newest_series'
                                                    in default_off) else True
                            channel_controls.append(control)
                        else:
                            pass
                    elif label == 'anime':
                        if 'anime' in categories:
                            control['label'] = config.get_localized_string(
                                70727) + ' - ' + config.get_localized_string(
                                    30124)
                            control['default'] = False if (
                                'include_in_newest'
                                in default_off) or ('include_in_newest_anime'
                                                    in default_off) else True
                            channel_controls.append(control)
                        else:
                            pass

                    else:
                        control['label'] = config.get_localized_string(
                            70727) + ' - ' + label.capitalize()
                        control['default'] = control['default'] if control[
                            'id'] not in default_off else False
                        channel_controls.append(control)

                elif control[
                        'id'] not in not_active and 'include_in_newest' not in control[
                            'id']:
                    if type(control['default']) == bool:
                        control['default'] = control['default'] if control[
                            'id'] not in default_off else False
                    channel_controls.append(control)

        if 'anime' in categories:
            for control in default_controls_renumber:
                if control['id'] not in str(channel_controls):
                    channel_controls.append(control)
                else:
                    pass
    else:
        return get_channel_json(channel_name).get('settings', list())
    return channel_controls
コード例 #11
0
ファイル: config.py プロジェクト: staycanuca/BUILDONLY
def verify_directories_created():
    import logger
    import filetools
    from resources.lib.platformcode import xbmc_library

    config_paths = [["librarypath", "library"], ["downloadpath", "downloads"],
                    ["downloadlistpath", "downloads/list"],
                    ["settings_path", "settings_channels"]]

    for path, default in config_paths:
        saved_path = get_setting(path)

        # Biblioteca
        if path == "librarypath":
            set_setting("library_version", "v4")
            if not saved_path:
                saved_path = xbmc_library.search_library_path()
                if saved_path:
                    set_setting(path, saved_path)

        if not saved_path:
            saved_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/" + default
            set_setting(path, saved_path)

        if get_setting("library_set_content") == True and path in [
                "librarypath", "downloadpath"
        ]:
            # logger.debug("library_set_content %s" % get_setting("library_set_content"))
            xbmc_library.add_sources(saved_path)

        saved_path = xbmc.translatePath(saved_path)
        if not filetools.exists(saved_path):
            logger.debug("Creating %s: %s" % (path, saved_path))
            filetools.mkdir(saved_path)

    config_paths = [["folder_movies", "CINE"], ["folder_tvshows", "SERIES"]]

    for path, default in config_paths:
        saved_path = get_setting(path)

        if not saved_path:
            saved_path = default
            set_setting(path, saved_path)

        content_path = filetools.join(get_library_path(), saved_path)
        if not filetools.exists(content_path):
            logger.debug("Creating %s: %s" % (path, content_path))
            if filetools.mkdir(content_path) and get_setting(
                    "library_set_content") == True:
                xbmc_library.set_content(default)

        elif get_setting("library_ask_set_content") == 2:
            xbmc_library.set_content(default)

    try:
        import scrapertools
        # Buscamos el archivo addon.xml del skin activo
        skindir = filetools.join(xbmc.translatePath("special://home"),
                                 'addons', xbmc.getSkinDir(), 'addon.xml')
        # Extraemos el nombre de la carpeta de resolución por defecto
        folder = ""
        data = filetools.read(skindir)
        res = scrapertools.find_multiple_matches(data, '(<res .*?>)')
        for r in res:
            if 'default="true"' in r:
                folder = scrapertools.find_single_match(r, 'folder="([^"]+)"')
                break

        # Comprobamos si existe en pelisalacarta y sino es así, la creamos
        default = filetools.join(get_runtime_path(), 'resources', 'skins',
                                 'Default')
        if folder and not filetools.exists(filetools.join(default, folder)):
            filetools.mkdir(filetools.join(default, folder))

        # Copiamos el archivo a dicha carpeta desde la de 720p si éste no existe o si el tamaño es diferente
        if folder and folder != '720p':
            for root, folders, files in filetools.walk(
                    filetools.join(default, '720p')):
                for f in files:
                    if not filetools.exists(filetools.join(default, folder, f)) or \
                          (filetools.getsize(filetools.join(default, folder, f)) !=
                           filetools.getsize(filetools.join(default, '720p', f))):
                        filetools.copy(filetools.join(default, '720p', f),
                                       filetools.join(default, folder, f),
                                       True)
    except:
        import traceback
        logger.error("Al comprobar o crear la carpeta de resolución")
        logger.error(traceback.format_exc())