Exemple #1
0
def cron_filename():
    """ Get crontab filename. """
    options = {
        'directory': 'config',
    }
    return weechat.string_eval_path_home(
        weechat.config_get_plugin("filename"), {}, {}, options)
Exemple #2
0
def test_strings():
    """Test string functions."""
    check(weechat.charset_set('iso-8859-15') == 1)
    check(weechat.charset_set('') == 1)
    check(weechat.iconv_to_internal('iso-8859-15', 'abc') == 'abc')
    check(weechat.iconv_from_internal('iso-8859-15', 'abcd') == 'abcd')
    check(weechat.gettext('abcdef') == 'abcdef')
    check(weechat.ngettext('file', 'files', 1) == 'file')
    check(weechat.ngettext('file', 'files', 2) == 'files')
    check(weechat.strlen_screen('abcd') == 4)
    check(weechat.string_match('abcdef', 'abc*', 0) == 1)
    check(weechat.string_match('abcdef', 'abc*', 1) == 1)
    check(weechat.string_match('ABCDEF', 'abc*', 1) == 0)
    check(weechat.string_match_list('abcdef', '*,!abc*', 0) == 0)
    check(weechat.string_match_list('ABCDEF', '*,!abc*', 1) == 1)
    check(weechat.string_match_list('def', '*,!abc*', 0) == 1)
    check(weechat.string_eval_path_home('test ${abc}', {}, {'abc': '123'}, {}) == 'test 123')
    check(weechat.string_mask_to_regex('test*mask') == 'test.*mask')
    check(weechat.string_has_highlight('my test string', 'test,word2') == 1)
    check(weechat.string_has_highlight_regex('my test string', 'test|word2') == 1)
    check(weechat.string_format_size(0) == '0 bytes')
    check(weechat.string_format_size(1) == '1 byte')
    check(weechat.string_format_size(2097152) == '2.10 MB')
    check(weechat.string_format_size(420000000) == '420.00 MB')
    check(weechat.string_remove_color('test', '?') == 'test')
    check(weechat.string_is_command_char('/test') == 1)
    check(weechat.string_is_command_char('test') == 0)
    check(weechat.string_input_for_buffer('test') == 'test')
    check(weechat.string_input_for_buffer('/test') == '')
    check(weechat.string_input_for_buffer('//test') == '/test')
    check(weechat.string_eval_expression("100 > 50", {}, {}, {"type": "condition"}) == '1')
    check(weechat.string_eval_expression("-50 < 100", {}, {}, {"type": "condition"}) == '1')
    check(weechat.string_eval_expression("18.2 > 5", {}, {}, {"type": "condition"}) == '1')
    check(weechat.string_eval_expression("0xA3 > 2", {}, {}, {"type": "condition"}) == '1')
    check(weechat.string_eval_expression("${buffer.full_name}", {}, {}, {}) == 'core.weechat')
Exemple #3
0
def test_strings():
    """Test string functions."""
    check(weechat.charset_set('iso-8859-15') == 1)
    check(weechat.charset_set('') == 1)
    check(weechat.iconv_to_internal('iso-8859-15', 'abc') == 'abc')
    check(weechat.iconv_from_internal('iso-8859-15', 'abcd') == 'abcd')
    check(weechat.gettext('abcdef') == 'abcdef')
    check(weechat.ngettext('file', 'files', 1) == 'file')
    check(weechat.ngettext('file', 'files', 2) == 'files')
    check(weechat.strlen_screen('abcd') == 4)
    check(weechat.string_match('abcdef', 'abc*', 0) == 1)
    check(weechat.string_eval_path_home('test ${abc}', {}, {'abc': '123'}, {}) == 'test 123')
    check(weechat.string_mask_to_regex('test*mask') == 'test.*mask')
    check(weechat.string_has_highlight('my test string', 'test,word2') == 1)
    check(weechat.string_has_highlight_regex('my test string', 'test|word2') == 1)
    check(weechat.string_remove_color('test', '?') == 'test')
    check(weechat.string_is_command_char('/test') == 1)
    check(weechat.string_is_command_char('test') == 0)
    check(weechat.string_input_for_buffer('test') == 'test')
    check(weechat.string_input_for_buffer('/test') == '')
    check(weechat.string_input_for_buffer('//test') == '/test')
    check(weechat.string_eval_expression("100 > 50", {}, {}, {"type": "condition"}) == '1')
    check(weechat.string_eval_expression("-50 < 100", {}, {}, {"type": "condition"}) == '1')
    check(weechat.string_eval_expression("18.2 > 5", {}, {}, {"type": "condition"}) == '1')
    check(weechat.string_eval_expression("0xA3 > 2", {}, {}, {"type": "condition"}) == '1')
    check(weechat.string_eval_expression("${buffer.full_name}", {}, {}, {}) == 'core.weechat')
Exemple #4
0
def bufsave_cmd(data, buffer, args):
    filename = weechat.buffer_get_string(
        buffer, 'localvar_server') + '.' + weechat.buffer_get_string(
            buffer,
            'localvar_channel')[1:] + '-' + time.strftime('%y_%m_%d') + '.log'
    filename = weechat.string_eval_path_home('%h/logs/' + filename, {}, {}, {})
    try:
        fp = open(filename, 'w')
    except:
        weechat.prnt('', 'Error writing to target file!')
        return weechat.WEECHAT_RC_OK
    own_lines = weechat.hdata_pointer(weechat.hdata_get('buffer'), buffer,
                                      'own_lines')
    if own_lines:
        line = weechat.hdata_pointer(weechat.hdata_get('lines'), own_lines,
                                     'first_line')
        hdata_line = weechat.hdata_get('line')
        hdata_line_data = weechat.hdata_get('line_data')
        while line:
            data = weechat.hdata_pointer(hdata_line, line, 'data')
            if data:
                date = weechat.hdata_time(hdata_line_data, data, 'date')
                if not isinstance(date, str):
                    date = time.strftime('%F %T', time.localtime(int(date)))
                fp.write('{0} {1} {2}\n'.format(
                    date,
                    cstrip(
                        weechat.hdata_string(hdata_line_data, data, 'prefix')),
                    cstrip(
                        weechat.hdata_string(hdata_line_data, data,
                                             'message'))))
            line = weechat.hdata_move(hdata_line, line, 1)
    fp.close()
    return weechat.WEECHAT_RC_OK
Exemple #5
0
def urlserver_filename():
    """Return name of file used to store list of urls."""
    options = {
        'directory': 'data',
    }
    return weechat.string_eval_path_home('%h/urlserver_list.txt', {}, {},
                                         options)
Exemple #6
0
def get_path():
    """ get logger path """
    options = {
        'directory': 'data',
    }
    return w.string_eval_path_home(
        w.config_string(w.config_get("logger.file.path")), {}, {}, options)
Exemple #7
0
def get_filename_with_path(filename):
    options = {
        'directory': 'data',
    }
    path = weechat.string_eval_path_home(OPTIONS['history_dir'], {}, {},
                                         options)
    return os.path.join(path, filename)
Exemple #8
0
def config_create_dir():
    options = {
        'directory': 'data',
    }
    dir = weechat.string_eval_path_home(OPTIONS['history_dir'], {}, {},
                                        options)
    if not os.path.isdir(dir):
        os.makedirs(dir, mode=0o700)
Exemple #9
0
def bufsave_cmd(data, buffer, args):
    ''' Callback for /bufsave command '''

    filename_raw = args

    if not filename_raw:
        w.command('', '/help %s' % SCRIPT_COMMAND)
        return w.WEECHAT_RC_OK

    filename = w.string_eval_path_home(filename_raw, {}, {}, {})

    if exists(filename):
        w.prnt('', 'Error: target file already exists!')
        return w.WEECHAT_RC_OK

    try:
        fp = open(filename, 'w')
    except:
        w.prnt('', 'Error writing to target file!')
        return w.WEECHAT_RC_OK

    version = w.info_get('version_number', '') or 0
    if int(version) >= 0x00030600:
        # use hdata with WeeChat >= 0.3.6 (direct access to data, very fast)
        own_lines = w.hdata_pointer(w.hdata_get('buffer'), buffer, 'own_lines')
        if own_lines:
            line = w.hdata_pointer(w.hdata_get('lines'), own_lines,
                                   'first_line')
            hdata_line = w.hdata_get('line')
            hdata_line_data = w.hdata_get('line_data')
            while line:
                data = w.hdata_pointer(hdata_line, line, 'data')
                if data:
                    date = w.hdata_time(hdata_line_data, data, 'date')
                    # since WeeChat 0.3.9, hdata_time returns long instead of string
                    if not isinstance(date, str):
                        date = time.strftime('%F %T',
                                             time.localtime(int(date)))
                    fp.write('%s %s %s\n' %(\
                            date,
                            cstrip(w.hdata_string(hdata_line_data, data, 'prefix')),
                            cstrip(w.hdata_string(hdata_line_data, data, 'message')),
                            ))
                line = w.hdata_move(hdata_line, line, 1)
    else:
        # use infolist with WeeChat <= 0.3.5 (full duplication of lines, slow and uses memory)
        infolist = w.infolist_get('buffer_lines', buffer, '')
        while w.infolist_next(infolist):
            fp.write('%s %s %s\n' %(\
                    w.infolist_time(infolist, 'date'),
                    cstrip(w.infolist_string(infolist, 'prefix')),
                    cstrip(w.infolist_string(infolist, 'message')),
                    ))
        w.infolist_free(infolist)

    fp.close()

    return w.WEECHAT_RC_OK
Exemple #10
0
def shutdown():
    options = {
        'directory': 'data',
    }
    for my_file in ['output_file', 'output_active_buffer']:
        filename = w.string_eval_path_home(my_file, {}, {}, options)
        if os.path.exists(filename):
            os.remove(filename)
    return w.WEECHAT_RC_OK
Exemple #11
0
def un_cache_dir():
    options = {
        'directory': 'cache',
    }
    filename = weechat.string_eval_path_home('%%h/%s' % SCRIPT_NAME, {}, {},
                                             options)
    if not os.path.isdir(filename):
        os.makedirs(filename, mode=0o700)
    return filename
Exemple #12
0
def bufsave_cmd(data, buffer, args):
    ''' Callback for /bufsave command '''

    filename_raw = args

    if not filename_raw:
        w.command('', '/help %s' %SCRIPT_COMMAND)
        return w.WEECHAT_RC_OK
    
    filename = w.string_eval_path_home(filename_raw, {}, {}, {})

    if exists(filename):
        w.prnt('', 'Error: target file already exists!')
        return w.WEECHAT_RC_OK

    try:
        fp = open(filename, 'w')
    except:
        w.prnt('', 'Error writing to target file!')
        return w.WEECHAT_RC_OK

    version = w.info_get('version_number', '') or 0
    if int(version) >= 0x00030600:
        # use hdata with WeeChat >= 0.3.6 (direct access to data, very fast)
        own_lines = w.hdata_pointer(w.hdata_get('buffer'), buffer, 'own_lines')
        if own_lines:
            line = w.hdata_pointer(w.hdata_get('lines'), own_lines, 'first_line')
            hdata_line = w.hdata_get('line')
            hdata_line_data = w.hdata_get('line_data')
            while line:
                data = w.hdata_pointer(hdata_line, line, 'data')
                if data:
                    date = w.hdata_time(hdata_line_data, data, 'date')
                    # since WeeChat 0.3.9, hdata_time returns long instead of string
                    if not isinstance(date, str):
                        date = time.strftime('%F %T', time.localtime(int(date)))
                    fp.write('%s %s %s\n' %(\
                            date,
                            cstrip(w.hdata_string(hdata_line_data, data, 'prefix')),
                            cstrip(w.hdata_string(hdata_line_data, data, 'message')),
                            ))
                line = w.hdata_move(hdata_line, line, 1)
    else:
        # use infolist with WeeChat <= 0.3.5 (full duplication of lines, slow and uses memory)
        infolist = w.infolist_get('buffer_lines', buffer, '')
        while w.infolist_next(infolist):
            fp.write('%s %s %s\n' %(\
                    w.infolist_time(infolist, 'date'),
                    cstrip(w.infolist_string(infolist, 'prefix')),
                    cstrip(w.infolist_string(infolist, 'message')),
                    ))
        w.infolist_free(infolist)

    fp.close()

    return w.WEECHAT_RC_OK
Exemple #13
0
def get_dir(filename):
    import os
    options = {
        'directory': 'data',
    }
    basedir = weechat.string_eval_path_home(weechat.config_get_plugin('path'),
                                            {}, {}, options)
    if not os.path.isdir(basedir):
        os.makedirs(basedir)
    return os.path.join(basedir, filename.lower())
Exemple #14
0
def setup():
	"""Load replacements from available resource."""

	global xml_path
	xml_path = weechat.string_eval_path_home("%h/latex_unicode.xml", "", "", "")

	if os.path.isfile(xml_path):
		setup_from_file()
	else:
		setup_from_url()
Exemple #15
0
def get_config(args):
    """get path to config file"""

    try:
        conf = args[1]
    except Exception:
        conf = w.config_get_plugin('file')
    options = {
        'directory': 'config',
    }
    return w.string_eval_path_home(conf, {}, {}, options)
Exemple #16
0
def load_factoids():
    """Load all factoids from file."""
    global FACTOIDS
    path = weechat.config_string(weechat.config_get("plugins.var.python.kwfactoids.path"))
    path = weechat.string_eval_path_home(path, {}, {}, {})
    try:
        with io.open(path, 'r', encoding='utf-8') as fh:
            FACTOIDS = json.load(fh)
        weechat.prnt("", "Loaded %d factoids." % len(FACTOIDS))
    except IOError as e:
        weechat.prnt("", "Failed to load factoids from %s. Reason: %s" % (len(path), e))
        return weechat.WEECHAT_RC_ERROR
    return weechat.WEECHAT_RC_OK
Exemple #17
0
def setup():
	"""Load replacements from available resource."""

	global xml_path
	options = {
		"directory": "cache",
	}
	xml_path = weechat.string_eval_path_home("%h/latex_unicode.xml", {}, {}, options)

	if os.path.isfile(xml_path):
		setup_from_file()
	else:
		setup_from_url()
Exemple #18
0
def load_factoids():
    """Load all factoids from file."""
    global FACTOIDS
    path = weechat.config_string(
        weechat.config_get("plugins.var.python.kwfactoids.path"))
    path = weechat.string_eval_path_home(path, {}, {}, {})
    try:
        with io.open(path, 'r', encoding='utf-8') as fh:
            FACTOIDS = json.load(fh)
        weechat.prnt("", "Loaded %d factoids." % len(FACTOIDS))
    except IOError as e:
        weechat.prnt(
            "", "Failed to load factoids from %s. Reason: %s" % (len(path), e))
        return weechat.WEECHAT_RC_ERROR
    return weechat.WEECHAT_RC_OK
Exemple #19
0
def write(my_file, content):
    if my_file == "":
        return
    options = {
        'directory': 'data',
    }
    my_file = w.string_eval_path_home(my_file, {}, {}, options)
    try:
        f = open(my_file, 'w')
    except IOError:
        w.prnt(
            '',
            'Error: %s is unable to open "%s", please select an appropriate location'
            % (name, my_file))
    else:
        f.writelines(content)
        f.close()
Exemple #20
0
    if server not in zncplayback_settings["servers"].split(","):
        return weechat.WEECHAT_RC_OK
    zncplayback_last_times[server] = int(time())
    write_last_times()
    return weechat.WEECHAT_RC_OK


if __name__ == "__main__" and import_ok:
    if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION,
                        SCRIPT_LICENSE, SCRIPT_DESCRIPTION, "", ""):
        options = {
            'directory': 'data',
        }
        SCRIPT_SAVEFILE = weechat.string_eval_path_home(
            '%%h/%s' % SCRIPT_SAVEFILE,
            {},
            {},
            options,
        )
        # Set default settings
        version = weechat.info_get("version_number", "") or 0
        for option, value in list(zncplayback_settings_default.items()):
            if weechat.config_is_set_plugin(option):
                zncplayback_settings[option] = weechat.config_get_plugin(
                    option)
            else:
                weechat.config_set_plugin(option, value[0])
                zncplayback_settings[option] = value[0]
            if int(version) >= 0x00030500:
                weechat.config_set_desc_plugin(
                    option, "%s (default: \"%s\")" % (value[1], value[0]))
Exemple #21
0
def confsave_cmd(data, buffer, args):
    args = args.split(" ")
    filename_raw = args[0]
    output_format = args[1]
    acceptable_formats = ["raw", "markdown", "commands"]
    output = ""
    currentheader = ""
    lastheader = ""

    if not filename_raw:
        w.prnt('', 'Error: filename not specified!')
        w.command('', '/help %s' % SCRIPT_COMMAND)
        return w.WEECHAT_RC_OK

    if output_format not in acceptable_formats:
        w.prnt('', 'Error: format incorrect or not specified!')
        w.command('', '/help %s' % SCRIPT_COMMAND)
        return w.WEECHAT_RC_OK

    filename = w.string_eval_path_home(filename_raw, {}, {}, {})
    infolist = w.infolist_get("option", "", "")
    variable_dict = {}
    if infolist:
        while w.infolist_next(infolist):
            infolist_name = w.infolist_string(infolist, "full_name")
            infolist_default = w.infolist_string(infolist, "default_value")
            infolist_value = w.infolist_string(infolist, "value")
            infolist_type = w.infolist_string(infolist, "type")
            if infolist_value != infolist_default:
                variable_dict[infolist_name] = {}
                variable_dict[infolist_name]['main'] = infolist_name.split(
                    ".")[0]
                variable_dict[infolist_name]['name'] = infolist_name
                variable_dict[infolist_name]['value'] = infolist_value
                variable_dict[infolist_name]['type'] = infolist_type
        w.infolist_free(infolist)

    if output_format == "markdown":
        output += "## weechat configuration"
        output += "\n*automatically generated using [" + SCRIPT_NAME + ".py](" + SCRIPT_LINK + ")*"
    # w.prnt("", str(variable_dict.values())) # debug
    for config in variable_dict.values():
        if output_format == "markdown":
            currentheader = config['main']
            if not ("password" in config['name']) and ("sec.data"
                                                       not in config['value']):
                if currentheader != lastheader:
                    output += "\n### " + config['main']
                    lastheader = currentheader

        if not ("password" in config['name']) and ("sec.data"
                                                   not in config['value']):
            write_name = config['name']
            if config['type'] == "string":
                write_value = "\"" + config['value'] + "\""
            else:
                write_value = config['value']
            if output_format == "markdown":
                output += "\n\t/set " + write_name + " " + write_value
            if output_format == "raw":
                output += "\n" + write_name + " = " + write_value
            if output_format == "commands":
                output += "\n/set " + write_name + " " + write_value
    output += "\n"
    # w.prnt("", "\n" + output) # debug

    if exists(filename):
        w.prnt('', 'Error: target file already exists!')
        return w.WEECHAT_RC_OK

    try:
        fp = open(filename, 'w')
    except:
        w.prnt('', 'Error writing to target file!')
        return w.WEECHAT_RC_OK

    # w.prnt("", "\n" + output)
    fp.write(output)
    w.prnt(
        "", "\nSuccessfully outputted to " + filename + " as " +
        output_format + "!")

    fp.close()

    return w.WEECHAT_RC_OK
Exemple #22
0
        except:
            print_help()
            return weechat.WEECHAT_RC_ERROR

        database.commit()
        weechat.prnt("", "Nick successfully removed from ignored.")

    return weechat.WEECHAT_RC_OK


if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE,
                    SCRIPT_DESC, "", ""):
    options = {
        'directory': 'data',
    }
    db_file = weechat.string_eval_path_home("%h/trigge.rs", {}, {}, options)
    if weechat.config_get_plugin('debug') == "":
        weechat.config_set_plugin('debug', "0")

    random.seed()

    if not os.path.isfile(db_file):
        create_db()

    check_db()

    weechat.hook_print("", "", "", 1, "search_trig_cb", "")
    weechat.hook_command(SCRIPT_NAME, SCRIPT_DESC,
                         "See `/triggerreply' for more information.", "", "",
                         "command_input_callback", "")
    """ fire every sec """
Exemple #23
0
        else:
            w.config_set_plugin(option, value[0])
            url_olde_settings[option] = value[0]
        if int(version) >= 0x00030500:
            w.config_set_desc_plugin(option, value[1])


def url_olde_config_cb(data, option, value):
    """Called each time an option is changed."""
    url_olde_load_config()
    return w.WEECHAT_RC_OK


if w.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION,
              SCRIPT_LICENSE, SCRIPT_DESC, '', ''):
    if IMPORT_ERR:
        w.prnt("", "You need sqlite3 to run this plugin.")
    options = {
        'directory': 'data',
    }
    DBFILE = w.string_eval_path_home("%h/olde.sqlite3", {}, {}, options)
    if not os.path.isfile(DBFILE):
        create_db()  # init on load if file doesn't exist.

    # load the config
    url_olde_load_config()
    # config changes are reloaded
    w.hook_config('plugins.var.python.' + SCRIPT_NAME + '.*', 'url_olde_config_cb', '')
    # catch urls in buffer and send to the cb
    w.hook_print('', 'irc_privmsg', '://', 1, 'search_urls_cb', '')
Exemple #24
0
def beinc_init():
    """
    Ran every time the script is (re)loaded
    It loads the config (.json) file and (re)loads its contents into memory
    beinc_init() will disable all notifications on failure
    """

    global enabled
    global target_list
    global global_values

    # global chans/nicks sets are used to speed up the filtering
    global_values = {}
    target_list = []
    custom_error = ''
    global_values['global_channel_messages_policy'] = False
    global_values['global_private_messages_policy'] = False
    global_values['global_notifications_policy'] = False
    global_values['use_current_buffer'] = False

    try:
        options = {
            'directory': 'config',
        }
        beinc_config_file_str = weechat.string_eval_path_home(
            '%h/beinc_weechat.json', {}, {}, options)
        beinc_prnt(f'Parsing {beinc_config_file_str}...')
        custom_error = 'load error'
        with open(beinc_config_file_str, 'r') as fp:
            config_dict = json.load(fp)
        custom_error = 'target parse error'
        global_values['use_current_buffer'] = bool(
            config_dict['irc_client'].get('use_current_buffer', False))
        if config_dict.get('config_version',
                           0) != BEINC_CURRENT_CONFIG_VERSION:
            beinc_prnt('WARNING: The version of the config-file: {0} ({1}) '
                       'does not correspond to the latest version supported '
                       'by this program ({2})\nCheck beinc_config_sample.json '
                       'for the newest features!'.format(
                           beinc_config_file_str,
                           config_dict.get('config_version', 0),
                           BEINC_CURRENT_CONFIG_VERSION))
        for target in config_dict['irc_client']['targets']:
            try:
                new_target = WeechatTarget(target)
            except Exception as e:
                beinc_prnt(f'Unable to add target: {e}')
                continue
            if new_target.channel_messages_policy:
                global_values['global_channel_messages_policy'] = True
            if new_target.private_messages_policy:
                global_values['global_private_messages_policy'] = True
            if new_target.notifications_policy:
                global_values['global_notifications_policy'] = True
            target_list.append(new_target)
            beinc_prnt(f'BEINC target "{new_target.name}" added')
        beinc_prnt('Done!')
    except Exception as e:
        beinc_prnt(f'ERROR: unable to parse {beinc_config_file_str}: '
                   f'{custom_error} - {e}\nBEINC is now disabled')
        enabled = False
        # do not return error / exit the script
        # in order to give a smoother opportunity to fix a 'broken' config
        return weechat.WEECHAT_RC_OK
    return weechat.WEECHAT_RC_OK