Ejemplo n.º 1
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')
Ejemplo n.º 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')
Ejemplo n.º 3
0
	def key(buffer):
		extra_vars = {}
		for helper_name, helper in sorted(helpers.items()):
			expanded = weechat.string_eval_expression(helper, {"buffer": buffer}, {}, {})
			extra_vars[helper_name] = expanded if case_sensitive else casefold(expanded)
		result = []
		for rule in rules:
			expanded = weechat.string_eval_expression(rule, {"buffer": buffer}, extra_vars, {})
			result.append(expanded if case_sensitive else casefold(expanded))
		return result
Ejemplo n.º 4
0
def main():
    '''Sets up WeeChat Growl notifications.'''
    # Initialize options.
    for option, value in SETTINGS.items():
        if not weechat.config_is_set_plugin(option):
            weechat.config_set_plugin(option, value)
    # Initialize Growl.
    name = "WeeChat"
    hostname = weechat.string_eval_expression(
        weechat.config_get_plugin('hostname'), {}, {}, {})
    password = weechat.string_eval_expression(
        weechat.config_get_plugin('password'), {}, {}, {})
    icon_path = os.path.join(weechat.info_get("weechat_dir", ""),
                             weechat.config_get_plugin('icon'))
    weechat.prnt('',
                 'Hostname: "{0}", Password: "******"'.format(hostname, password))
    try:
        icon = open(icon_path, "rb").read()
    except IOError:
        weechat.prnt(
            '', 'Weechat-Growl: {0} could not be opened. '.format(icon_path) +
            'Please make sure it exists.')
        icon = None

    notifications = [
        'Public', 'Private', 'Action', 'Notice', 'Invite', 'Highlight',
        'Server', 'Channel', 'DCC', 'WeeChat'
    ]
    if len(hostname) == 0:
        hostname = ''
    if len(password) == 0:
        password = ''
    growl = GrowlNotifier(applicationName=name,
                          hostname=hostname,
                          password=password,
                          notifications=notifications,
                          applicationIcon=icon)
    try:
        growl.register()
    except Exception as error:
        weechat.prnt('', 'growl: {0}'.format(error))
    STATE['growl'] = growl
    STATE['icon'] = icon
    # Register hooks.
    weechat.hook_signal('irc_server_connected', 'cb_irc_server_connected', '')
    weechat.hook_signal('irc_server_disconnected',
                        'cb_irc_server_disconnected', '')
    weechat.hook_signal('upgrade_ended', 'cb_upgrade_ended', '')
    weechat.hook_print('', '', '', 1, 'cb_process_message', '')
Ejemplo n.º 5
0
def privmsg(data, signal, signal_data):
    (server, signal) = signal.split(',')
    channels = wc.config_get_plugin('channels').replace(',', '|')
    consumer_key = wc.config_get_plugin('consumer_key')
    consumer_secret = wc.config_get_plugin('consumer_secret')
    access_token_key = wc.config_get_plugin('access_token_key')
    access_token_secret = wc.config_get_plugin('access_token_secret')
    sec = re.compile('^\${sec\.data\.(.*)}$')
    if sec.match(consumer_key):
        consumer_key = wc.string_eval_expression(consumer_key, {}, {}, {})
    if sec.match(consumer_secret):
        consumer_secret = wc.string_eval_expression(consumer_secret, {}, {}, {})
    if sec.match(access_token_key):
        access_token_key = wc.string_eval_expression(access_token_key, {}, {}, {})
    if sec.match(access_token_secret):
        access_token_secret = wc.string_eval_expression(access_token_secret, {}, {}, {})
    bots_list = wc.config_get_plugin('other_bots').split(',')
    details = wc.info_get_hashtable('irc_message_parse', {'message': signal_data, 'server': server})
    twitter_regex_match = re.compile(r'(.*https?://)?twitter\.com/.*/status/([0-9]{18})(.*)').match(details['text'])
    buffer_name = details['channel']
    buffer_pointer = wc.info_get('irc_buffer', '%s,%s' % (server, buffer_name))
    channels_regex = re.compile(r'(%s)' % (channels), re.I)
    bots_exist = False
    if channels_regex.match(buffer_name) and twitter_regex_match:
        if not bots_list == 'not_set':
            for other_bots in bots_list:
                bots_test = wc.nicklist_search_nick(buffer_pointer, '', other_bots)
                if bots_test:
                    bots_exist = True
        if not bots_exist:
            if consumer_key == 'not_set':
                wc.command('', r'/msg {0} Twitter consumer_key not set.'.format(buffer_name))
            elif consumer_secret == 'not_set':
                wc.command('', r'/msg {0} Twitter consumer_secret not set.'.format(buffer_name))
            elif access_token_key == 'not_set':
                wc.command('', r'/msg {0} Twitter access_token_key not set.'.format(buffer_name))
            elif access_token_secret == 'not_set':
                wc.command('', r'/msg {0} Twitter access_token_secret not set.'.format(buffer_name))
            else:
                tweet_id = twitter_regex_match.group(2)
                tweet = TwitterAPI(consumer_key, consumer_secret, access_token_key, access_token_secret).request('statuses/show/:{0}'.format(tweet_id))
                try:
                    tweet_message = tweet.json()['text'].replace('\n', ' ').encode('utf-8')
                    tweet_message = HTMLParser().unescape(tweet_message)
                    tweet_user = tweet.json()['user']['screen_name'].encode('utf-8')
                    wc.command('', r'/msg {0} [Twitter] "{1}" by @{2}'.format(buffer_name, tweet_message, tweet_user))
                except:
                    wc.command('', r'/msg {0} [Twitter] Error getting tweet info.'.format(buffer_name))
    return wc.WEECHAT_RC_OK
Ejemplo n.º 6
0
def generate_totp(server, period=30, buffer=""):
    print_debug('generate_totp(%s)' % server)
    seed = weechat.string_eval_expression("${sec.data.%s_seed}" % server, {},
                                          {}, {})

    if not seed:
        sprint("No OATH-TOTP secret set, use: /uotp add %s <seed>" % server,
               buffer)
        return None

    if len(seed) == 40:  # Assume hex format
        seed = unhexlify(seed)
    else:
        seed = b32decode(seed.replace(" ", ""), True)

    def _ord(b):
        if sys.version_info[0] < 3 or type(b) == str:
            return ord(b)
        return b

    t = pack(">Q", int(time() / period))
    _hmac = hmac.new(seed, t, sha1).digest()
    o = _ord(_hmac[19]) & 15
    otp = (unpack(">I", _hmac[o:o + 4])[0] & 0x7fffffff) % 1000000

    return '%06d' % otp
Ejemplo n.º 7
0
def encrypt(text):
    encryption_password = weechat.config_get_plugin("encryption_password")

    # decrypt the password if it is stored as secured data
    if encryption_password.startswith("${sec."):
        encryption_password = weechat.string_eval_expression(encryption_password, {}, {}, {})

    if PY3:
        text = text.encode("UTF-8")

    command="openssl enc -aes-128-cbc -salt -base64 -md md5 -A -pass env:OpenSSLEncPW"
    opensslenv = os.environ.copy();
    # Unknown whether the encryption password should or should not be
    # (UTF8-)encoded before being passed to the environment in python 3.
    opensslenv['OpenSSLEncPW'] = encryption_password
    output, errors = Popen(shlex.split(command), stdin=PIPE, stdout=PIPE,
                           stderr=PIPE,env=opensslenv).communicate(text + b" ")
    output = output.replace(b"/", b"_")
    output = output.replace(b"+", b"-")
    output = output.replace(b"=", b"")

    if PY3:
        output = output.decode("UTF-8")

    return output
Ejemplo n.º 8
0
def redirect_isonhandler(data, signal, hashtable):
    if hashtable["output"] == "":
        return weechat.WEECHAT_RC_OK

    # ISON_nicks contains nicks that are online on server (separated with space)
    # nicks in ISON_nicks are lowercase
    message, ISON_nicks = hashtable["output"].split(":")[1:]
    ISON_nicks = [nick.lower() for nick in ISON_nicks.split()]

    for nick in server_nicks(hashtable["server"]):
        mynick = weechat.info_get("irc_nick", hashtable["server"])

        if nick.lower() == mynick.lower():
            return weechat.WEECHAT_RC_OK
        elif nick.lower() not in ISON_nicks and nick != "":
            # get password for given server (evaluated)
            if int(version) >= 0x00040200:
                password = weechat.string_eval_expression(
                    weechat.config_get_plugin("%s.password" % hashtable["server"]), {}, {}, {}
                )
            else:
                password = weechat.config_get_plugin("%s.password" % hashtable["server"])

            grabnick(hashtable["server"], nick)  # get your nick back

            if password != "" and OPTIONS["nickserv"] != "":
                # command stored in "keepnick.nickserv" option
                t = Template(OPTIONS["nickserv"])
                run_msg = t.safe_substitute(server=hashtable["server"], passwd=password)
                weechat.command("", run_msg)
    return weechat.WEECHAT_RC_OK
Ejemplo n.º 9
0
def fish_secure_key_cb(data, option, value):
    global fish_secure_key, fish_secure_cipher

    fish_secure_key = weechat.config_string(
        weechat.config_get("fish.secure.key")
    )

    if fish_secure_key == "":
        fish_secure_cipher = None
        return weechat.WEECHAT_RC_OK

    if fish_secure_key[:6] == "${sec.":
        decrypted = weechat.string_eval_expression(
            fish_secure_key, {}, {}, {}
        )
        if decrypted:
            fish_secure_cipher = Blowfish(decrypted)
            return weechat.WEECHAT_RC_OK
        else:
            weechat.config_option_set(fish_config_option["key"], "", 0)
            weechat.prnt("", "Decrypt sec.conf first\n")
            return weechat.WEECHAT_RC_OK

    if fish_secure_key != "":
        fish_secure_cipher = Blowfish(fish_secure_key)

    return weechat.WEECHAT_RC_OK
Ejemplo n.º 10
0
def process_pushbullet_cb(data, url, status, response, err):
    body = None
    headers = {}
    lines = response.rstrip().splitlines()
    status_code = int(lines.pop(0).split()[1])
    for line in lines:
        if body == "":
            body += line
            continue
        header_line = line.split(":", 2)
        if len(header_line) != 2:
            body = ""
            continue
        headers[header_line[0].strip()] = header_line[1].strip()

    # response is the string of http body
    if status == w.WEECHAT_HOOK_PROCESS_ERROR:
        w.prnt("", "[weebullet] Error sending to pushbullet: %s - %s" % (status, url))
        return w.WEECHAT_RC_ERROR

    if status_code is 401 or status_code is 403:
        w.prnt("", "[weebullet] Invalid API Token: %s" % (w.string_eval_expression(w.config_get_plugin("api_key"), {}, {}, {})))
        return w.WEECHAT_RC_ERROR
    if status_code is not 200:
        w.prnt("", "[weebullet] Error sending to pushbullet: %s - %s - %s" % (url, status_code, body))
        return w.WEECHAT_RC_ERROR

    return w.WEECHAT_RC_OK
Ejemplo n.º 11
0
def substitute_colors(text,window):
    if int(version) >= 0x00040200:
        bufpointer = weechat.window_get_pointer(window,"buffer")
        return weechat.string_eval_expression(text, {"buffer": bufpointer}, {}, {})
#        return weechat.string_eval_expression(text,{},{},{})
    # substitute colors in output
    return re.sub(regex_color, lambda match: weechat.color(match.group(1)), text)
Ejemplo n.º 12
0
def process_join_cb(data, url, status, response, err):
    body = None
    headers = {}
    lines = response.rstrip().splitlines()
    status_code = int(lines.pop(0).split()[1])
    for line in lines:
        if body == "":
            body += line
            continue
        header_line = line.split(":", 2)
        if len(header_line) != 2:
            body = ""
            continue
        headers[header_line[0].strip()] = header_line[1].strip()

    # response is the string of http body
    if status == w.WEECHAT_HOOK_PROCESS_ERROR:
        w.prnt("", "[weejoin] Error sending to join: %s - %s" % (status, url))
        return w.WEECHAT_RC_ERROR

    if status_code == 401 or status_code == 403:
        w.prnt(
            "", "[weejoin] Invalid API Token: %s" % (w.string_eval_expression(
                w.config_get_plugin("api_key"), {}, {}, {})))
        return w.WEECHAT_RC_ERROR
    if status_code != 200:
        w.prnt(
            "", "[weejoin] Error sending to join: %s - %s - %s" %
            (url, status_code, body))
        return w.WEECHAT_RC_ERROR

    return w.WEECHAT_RC_OK
Ejemplo n.º 13
0
def privmsg(data, signal, signal_data):
    (server, signal) = signal.split(",")
    channels = wc.config_get_plugin('channels').replace(',', '|')
    api_key = wc.config_get_plugin('api_key')
    if re.match('^\${sec\.data\.(.*)}$', api_key):
        api_key = wc.string_eval_expression(api_key, {}, {}, {})
    bots_list = wc.config_get_plugin('other_bots').split(",")
    details = wc.info_get_hashtable("irc_message_parse", {"message": signal_data, "server": server})
    youtube_regex_match = re.compile(r'(.*https?://)?(www\.)?(youtube|youtu|youtube-nocookie)\.(com|be)/(watch\?v=|embed/|v/|.+\?v=)?([a-zA-Z0-9_-]{11})').match(details['text'])
    buffer_name = details['channel']
    buffer_pointer = wc.info_get("irc_buffer", "%s,%s" % (server, buffer_name))
    channels_regex = re.compile(r'(%s)' % (channels), re.I)
    bots_exist = False
    if channels_regex.match(buffer_name) and youtube_regex_match:
        if not bots_list == "not_set":
            for other_bots in bots_list:
                bots_test = wc.nicklist_search_nick(buffer_pointer, "", other_bots)
                if bots_test:
                    bots_exist = True
        if not bots_exist:
            if not api_key == "not_set":
                vid_id = youtube_regex_match.group(6)
                rvt = requests.get('https://www.googleapis.com/youtube/v3/videos/?id={0}&part=snippet&key={1}'.format(vid_id, api_key))
                rvc = requests.get('https://www.googleapis.com/youtube/v3/videos/?id={0}&part=statistics&key={1}'.format(vid_id, api_key))
                try:
                    vid_title = rvt.json()['items'][0]['snippet']['title'].encode('utf-8')
                    vid_channel = rvt.json()['items'][0]['snippet']['channelTitle'].encode('utf-8')
                    vid_views = rvc.json()['items'][0]['statistics']['viewCount']
                    wc.command("", r"/msg {0} [Youtube] {1} | Channel: {2} | Views: {3}".format(buffer_name, vid_title, vid_channel, vid_views))
                except:
                    wc.command("", r"/msg {0} [Youtube] Error getting video info.".format(buffer_name))
            else:
                wc.command("", r"/msg {0} Youtube api key not set.".format(buffer_name))
    return wc.WEECHAT_RC_OK
Ejemplo n.º 14
0
def redirect_isonhandler(data, signal, hashtable):
    if hashtable['output'] == '':
        return weechat.WEECHAT_RC_OK

    # ISON_nicks contains nicks that are online on server (separated with space)
    # nicks in ISON_nicks are lowercase
    message, ISON_nicks = hashtable['output'].split(':')[1:]
    ISON_nicks = [nick.lower() for nick in ISON_nicks.split()]

    for nick in server_nicks(hashtable['server']):
        mynick = weechat.info_get('irc_nick', hashtable['server'])

        if nick.lower() == mynick.lower():
            return weechat.WEECHAT_RC_OK
        elif nick.lower() not in ISON_nicks and nick != '':
            # get password for given server (evaluated)
            if int(version) >= 0x00040200:
                password = weechat.string_eval_expression(
                    weechat.config_get_plugin('%s.password' %
                                              hashtable['server']), {}, {}, {})
            else:
                password = weechat.config_get_plugin('%s.password' %
                                                     hashtable['server'])

            grabnick(hashtable['server'], nick)  # get your nick back

            if password != '' and OPTIONS['nickserv'] != '':
                # command stored in "keepnick.nickserv" option
                t = Template(OPTIONS['nickserv'])
                run_msg = t.safe_substitute(server=hashtable['server'],
                                            passwd=password)
                weechat.command('', run_msg)
    return weechat.WEECHAT_RC_OK
Ejemplo n.º 15
0
def send_push(title, body):
    global last_notification

    interval = w.config_get_plugin("min_notify_interval")
    if interval is not None and interval != "" and int(interval) != 0:
        interval = int(interval)

        earliest_notification = last_notification + int(interval)

        if last_notification is not None and time.time(
        ) <= earliest_notification:
            debug("Too soon since last notification, skipping")
            return w.WEECHAT_RC_OK

    last_notification = time.time()

    # check to see if the relay is connected, ignore if so
    check_relays = w.config_string_to_boolean(
        w.config_get_plugin('ignore_on_relay'))
    CONNECTED_RELAY = False
    if check_relays:
        infolist = w.infolist_get('relay', '', '')
        if infolist:
            while w.infolist_next(infolist):
                status = w.infolist_string(infolist, 'status_string')
                if status == 'connected':
                    CONNECTED_RELAY = True
                    break
            w.infolist_free(infolist)

    if CONNECTED_RELAY is True:
        # we have a relay conected, don't notify
        debug("Relay is connected, not sending push.")
        return w.WEECHAT_RC_OK

    debug("Sending push.  Title: [%s], body: [%s]" % (title, body))

    apikey = w.string_eval_expression(w.config_get_plugin("api_key"), {}, {},
                                      {})
    apiurl = "https://%[email protected]/v2/pushes" % (apikey)
    timeout = 20000  # FIXME - actually use config
    if len(title) is not 0 or len(body) is not 0:
        deviceiden = w.config_get_plugin("device_iden")
        if deviceiden == "all":
            payload = urllib.parse.urlencode({
                'type': 'note',
                'title': title,
                'body': body
            })
        else:
            payload = urllib.parse.urlencode({
                'type': 'note',
                'title': title,
                'body': body,
                'device_iden': deviceiden
            })
        w.hook_process_hashtable("url:" + apiurl, {
            "postfields": payload,
            "header": "1"
        }, timeout, "process_pushbullet_cb", "")
Ejemplo n.º 16
0
def keys_create_option_cb(data, config_file, section, option, value):
    if not keys_check_option_cb('', option, value):
        weechat.prnt('',
                     "WeeSodium keys must be stored using WeeChat's secured "
                     "data storage. See /help secure for info on this.")
        return weechat.WEECHAT_CONFIG_OPTION_SET_ERROR

    option_split = option.split('.')
    if len(option_split) != 2:
        weechat.prnt('',
                     "Both a server and a channel are required to be entered "
                     "as the key for the config option. For example: "
                     "/set weesodium.keys.example.#weesodium "
                     "${sec.data.wskey}")
        return weechat.WEECHAT_CONFIG_OPTION_SET_ERROR

    weeopt = weechat.config_new_option(config_file, section, option, 'string',
                                       'key', '', 0, 0, '', value, 0,
                                       'keys_check_option_cb', '', '', '',
                                       '', '')
    if not weeopt:
        return weechat.WEECHAT_CONFIG_OPTION_SET_ERROR

    option_split = option.split('.')
    if len(option_split) == 2 and value.startswith('${sec.data.'):
        channel_key = weechat.string_eval_expression(value, {}, {}, {})
        channel_data[option] = WeeSodiumChannel(channel_key)

    return weechat.WEECHAT_CONFIG_OPTION_SET_OK_CHANGED
Ejemplo n.º 17
0
def fish_secure():
    global fish_secure_key, fish_secure_cipher

    fish_secure_key = weechat.config_string(fish_config_option["key"])

    # if blank, do nothing
    if fish_secure_key == "":
        fish_success()
        return

    # if ${sec.data.fish}, check if sec.conf is decrypted
    # and decrypt
    elif fish_secure_key[:6] == "${sec.":
        decrypted = weechat.string_eval_expression(fish_secure_key, {}, {}, {})

        if decrypted:
            fish_secure_cipher = Blowfish(decrypted)
            fish_decrypt_keys()
            fish_success()
            return

        else:
            global SCRIPT_NAME
            fish_secure_error()
            weechat.command(weechat.current_buffer(),
                            "/wait 1ms /python unload %s" % SCRIPT_NAME)
            return

    # if key is neither ${sec.data.fish} or ""
    # encrypt/decrypt with user supplied, plain text key
    if fish_secure_key != "":
        fish_secure_cipher = Blowfish(fish_secure_key)
        fish_decrypt_keys()
        fish_success()
        return
Ejemplo n.º 18
0
def fish_secure_key_cb(data, option, value):
    global fish_secure_key, fish_secure_cipher

    fish_secure_key = weechat.config_string(
        weechat.config_get("fish.secure.key")
    )

    if fish_secure_key == "":
        fish_secure_cipher = None
        return weechat.WEECHAT_RC_OK

    if fish_secure_key[:6] == "${sec.":
        decrypted = weechat.string_eval_expression(
            fish_secure_key, {}, {}, {}
        )
        if decrypted:
            fish_secure_cipher = Blowfish(decrypted)
            return weechat.WEECHAT_RC_OK
        else:
            weechat.config_option_set(fish_config_option["key"], "", 0)
            weechat.prnt("", "Decrypt sec.conf first\n")
            return weechat.WEECHAT_RC_OK

    if fish_secure_key != "":
        fish_secure_cipher = Blowfish(fish_secure_key)

    return weechat.WEECHAT_RC_OK
Ejemplo n.º 19
0
def disabled_servers():
    """ Return a list of configured TOTP servers that are currently disabled. """
    serverlist = get_irc_servers()
    server_seed_list = [server for server in serverlist
                        if weechat.string_eval_expression("${sec.data.%s_seed}" % server, {}, {}, {})
                        and server not in get_config_as_list('otp_server_names')]
    return [s for s in server_seed_list if s in serverlist]
Ejemplo n.º 20
0
def substitute_colors(text,window):
    if int(version) >= 0x00040200:
        bufpointer = weechat.window_get_pointer(window,"buffer")
        return weechat.string_eval_expression(text, {"buffer": bufpointer}, {}, {})
#        return weechat.string_eval_expression(text,{},{},{})
    # substitute colors in output
    return re.sub(regex_color, lambda match: weechat.color(match.group(1)), text)
Ejemplo n.º 21
0
def cmd_help(data, buffer, args):
    # Get current list of ignored channels in list form
    ignored_channels = get_ignored_channels()

    # Used for checking for ignore/unignore commands and getting the arguments
    ignore_command = re.match("^ignore\s+(.+)", args)
    unignore_command = re.match("^unignore\s+(.+)", args)

    if (ignore_command is not None):
        channels_to_ignore = ignore_command.group(1).split(' ')

        for channel in channels_to_ignore:
            if channel not in ignored_channels:
                ignored_channels.append(channel)

        w.config_set_plugin("ignored_channels", ','.join(ignored_channels))
        w.prnt(
            "", "Updated. Ignored channels: %s" %
            w.config_get_plugin("ignored_channels"))
    elif (unignore_command is not None):
        channels_to_unignore = unignore_command.group(1).split(' ')

        for channel in channels_to_unignore:
            if channel in ignored_channels:
                ignored_channels.remove(channel)

        w.config_set_plugin("ignored_channels", ','.join(ignored_channels))
        w.prnt(
            "", "Updated. Ignored channels: %s" %
            w.config_get_plugin("ignored_channels"))
    elif (args == "listignores"):
        w.prnt(
            "",
            "Ignored channels: %s" % w.config_get_plugin("ignored_channels"))
    elif (args == "listdevices"):
        apikey = w.string_eval_expression(w.config_get_plugin("api_key"), {},
                                          {}, {})
        apiurl = "https://joinjoaomgcd.appspot.com/_ah/api/registration/v1/listDevices?apikey=%s" % (
            apikey)
        w.hook_process("url:" + apiurl, 20000, "process_devicelist_cb", "")
    else:
        w.prnt(
            "", """
WeeJoin requires an API key from your Join account to work. Set your API key with (evaluated):
    /set plugins.var.python.weejoin.api_key <KEY>

WeeJoin will by default only send notifications when you are marked away on IRC. You can change this with:
    /set plugins.var.python.weejoin.away_only [0|1]

WeeJoin will by default send to all devices associated with your Join account. You can change this with:
    /set plugins.var.python.weejoin.device_iden <ID>

WeeJoin can ignore repeated notifications if they arrive too often.  You can set this with (0 or blank to disable):
    /set plugins.var.python.weejoin.min_notify_interval <NUMBER>

You can get a list of your devices from the Join website, or by using
    /weejoin listdevices
""")
    return w.WEECHAT_RC_OK
Ejemplo n.º 22
0
def configured_servers():
    """ Return a lost of servers with an existing seed. """
    serverlist = get_irc_servers()
    return [
        s for s in serverlist
        if weechat.string_eval_expression("${sec.data.%s_seed}" %
                                          s, {}, {}, {})
    ]
Ejemplo n.º 23
0
def main() -> None:
    if not weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION,
                            SCRIPT_LICENSE, SCRIPT_DESC, "", ""):
        return

    tmux = weechat.string_eval_expression("${env:TMUX}", {}, {}, {})
    kitty = weechat.string_eval_expression("${env:KITTY_LISTEN_ON}", {}, {},
                                           {})
    if tmux:
        weechat.hook_command(SCRIPT_NAME, SCRIPT_DESC, "", "", "",
                             "fzf_tmux_command_cb", "")
    elif kitty:
        weechat.hook_command(SCRIPT_NAME, SCRIPT_DESC, "", "", "",
                             "fzf_kitty_command_cb", "")
    else:
        print_error(
            "Error: fzf.py currently only supports being run inside tmux or kitty"
        )
Ejemplo n.º 24
0
def remove_server(server, remove_seed=False):
    """ Remove server from the plugin configuration. """
    if remove_seed and weechat.string_eval_expression("${sec.data.%s_seed}" % server, {}, {}, {}):
        weechat.command("", "/secure del %s_seed" % server)

    servers = get_config_as_list("otp_server_names")
    if server in servers:
        servers = [v for v in servers if v != server]
        weechat.config_set_plugin("otp_server_names", ','.join(servers))
Ejemplo n.º 25
0
def disabled_servers():
    """ Return a list of configured TOTP servers that are currently disabled. """
    serverlist = get_irc_servers()
    server_seed_list = [
        server for server in serverlist
        if weechat.string_eval_expression("${sec.data.%s_seed}" %
                                          server, {}, {}, {})
        and server not in get_config_as_list('otp_server_names')
    ]
    return [s for s in server_seed_list if s in serverlist]
Ejemplo n.º 26
0
def remove_server(server, remove_seed=False):
    """ Remove server from the plugin configuration. """
    if remove_seed and weechat.string_eval_expression(
            "${sec.data.%s_seed}" % server, {}, {}, {}):
        weechat.command("", "/secure del %s_seed" % server)

    servers = get_config_as_list("otp_server_names")
    if server in servers:
        servers = [v for v in servers if v != server]
        weechat.config_set_plugin("otp_server_names", ','.join(servers))
Ejemplo n.º 27
0
def bar_item_build_cb(data, item, window):
    """Update the alibnotify bar item to reflect current state"""
    if STATE['is_muted']:
        bar_text = 'notifications: muted'
        if 'mute_time' in STATE and STATE['mute_time'] > 0:
            bar_text += ' (%dm)' % STATE['mute_time']
        # Colour the text red
        bar_text = weechat.string_eval_expression('${color:red}%s' % bar_text,
                                                  {}, {}, {})
        return bar_text
    else:
        return ''
Ejemplo n.º 28
0
def show_notification(chan, nick, message):
    API_TOKEN = weechat.config_get_plugin("api_token")

    # decrypt the API token if it is stored as secured data
    if API_TOKEN.startswith("${sec."):
        API_TOKEN = weechat.string_eval_expression(API_TOKEN, {}, {}, {})

    if API_TOKEN != "":
        url = "https://irssinotifier.appspot.com/API/Message"
        postdata = urllib.urlencode({'apiToken':API_TOKEN,'nick':encrypt(nick),'channel':encrypt(chan),'message':encrypt(message),'version':13})
        version = weechat.info_get("version_number", "") or 0
        hook1 = weechat.hook_process_hashtable("url:"+url, { "postfields":  postdata}, 2000, "", "")
Ejemplo n.º 29
0
def main() -> None:
    if not weechat.register(
        SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "", ""
    ):
        return

    tmux = weechat.string_eval_expression("${env:TMUX}", {}, {}, {})
    if not tmux:
        print_error("Error: fzf.py currently only supports being run inside tmux")
        return

    weechat.hook_command(SCRIPT_NAME, SCRIPT_DESC, "", "", "", "fzf_command_cb", "")
Ejemplo n.º 30
0
def urlserver_check_auth(data):
    """Check user/password to access a page/URL."""
    global urlserver_settings
    if not urlserver_settings['http_auth']:
        return True
    http_auth = weechat.string_eval_expression(urlserver_settings['http_auth'],
                                               {}, {}, {})
    auth = re.search('^Authorization: Basic (\S+)$', data,
                     re.MULTILINE | re.IGNORECASE)
    if auth and (base64_decode(auth.group(1)).decode('utf-8') == http_auth):
        return True
    return False
Ejemplo n.º 31
0
def urlserver_check_auth(data):
    """Check user/password to access a page/URL."""
    global urlserver_settings
    if not urlserver_settings['http_auth']:
        return True
    http_auth = weechat.string_eval_expression(
        urlserver_settings['http_auth'], {}, {}, {})
    auth = re.search('^Authorization: Basic (\S+)$', data,
                     re.MULTILINE | re.IGNORECASE)
    if auth and (base64_decode(auth.group(1)).decode('utf-8') == http_auth):
        return True
    return False
Ejemplo n.º 32
0
def fish_secure_genkey(buffer):
    global fish_secure_cipher, fish_config_option

    newKey = blowcrypt_b64encode(urandom(32))

    # test to see if sec.conf decrypted
    weechat.command(buffer, "/secure set fish test")
    decrypted = weechat.string_eval_expression("${sec.data.fish}", {}, {}, {})

    if decrypted == "test":
        weechat.config_option_set(fish_config_option["key"],
                                  "${sec.data.fish}", 0)
        fish_secure_cipher = Blowfish(newKey)
        weechat.command(buffer, "/secure set fish %s" % newKey)
Ejemplo n.º 33
0
def cmd_help(data, buffer, args):
    # Get current list of ignored channels in list form
    ignored_channels = get_ignored_channels()

    # Used for checking for ignore/unignore commands and getting the arguments
    ignore_command = re.match("^ignore\s+(.+)", args)
    unignore_command = re.match("^unignore\s+(.+)", args)

    if(ignore_command is not None):
        channels_to_ignore = ignore_command.group(1).split(' ')

        for channel in channels_to_ignore:
            if channel not in ignored_channels:
                ignored_channels.append(channel)

        w.config_set_plugin("ignored_channels", ','.join(ignored_channels))
        w.prnt("", "Updated. Ignored channels: %s" % w.config_get_plugin("ignored_channels"))
    elif(unignore_command is not None):
        channels_to_unignore = unignore_command.group(1).split(' ')

        for channel in channels_to_unignore:
            if channel in ignored_channels:
                ignored_channels.remove(channel)

        w.config_set_plugin("ignored_channels", ','.join(ignored_channels))
        w.prnt("", "Updated. Ignored channels: %s" % w.config_get_plugin("ignored_channels"))
    elif(args == "listignores"):
        w.prnt("", "Ignored channels: %s" % w.config_get_plugin("ignored_channels"))
    elif(args == "listdevices"):
        apikey = w.string_eval_expression(w.config_get_plugin("api_key"), {}, {}, {})
        apiurl = "https://%[email protected]/v2/devices" % (apikey)
        w.hook_process("url:" + apiurl, 20000, "process_devicelist_cb", "")
    else:
        w.prnt("", """
Weebullet requires an API key from your Pushbullet account to work. Set your API key with (evaluated):
    /set plugins.var.python.weebullet.api_key <KEY>

Weebullet will by default only send notifications when you are marked away on IRC. You can change this with:
    /set plugins.var.python.weebullet.away_only [0|1]

Weebullet will by default send to all devices associated with your Pushbullet account. You can change this with:
    /set plugins.var.python.weebullet.device_iden <ID>

Weebullet can ignore repeated notifications if they arrive too often.  You can set this with (0 or blank to disable):
    /set plugins.var.python.weebullet.min_notify_interval <NUMBER>

You can get a list of your devices from the Pushbullet website, or by using
    /weebullet listdevices
""")
    return w.WEECHAT_RC_OK
Ejemplo n.º 34
0
def encrypt(text):
    encryption_password = weechat.config_get_plugin("encryption_password")

    # decrypt the password if it is stored as secured data
    if encryption_password.startswith("${sec."):
        encryption_password = weechat.string_eval_expression(encryption_password, {}, {}, {})

    command="openssl enc -aes-128-cbc -salt -base64 -md md5 -A -pass env:OpenSSLEncPW"
    opensslenv = os.environ.copy();
    opensslenv['OpenSSLEncPW'] = encryption_password
    output,errors = Popen(shlex.split(command),stdin=PIPE,stdout=PIPE,stderr=PIPE,env=opensslenv).communicate(text+" ")
    output = string.replace(output,"/","_")
    output = string.replace(output,"+","-")
    output = string.replace(output,"=","")
    return output
Ejemplo n.º 35
0
def keys_read_option_cb(data, config_file, section, option, value):
    """Read option callback: load keys from config options"""

    weeopt = weechat.config_new_option(config_file, section, option, 'string',
                                       'key', '', 0, 0, '', value, 0,
                                       'keys_check_option_cb', '', '', '',
                                       '', '')
    if not weeopt:
        return weechat.WEECHAT_CONFIG_OPTION_SET_ERROR

    option_split = option.split('.')
    if len(option_split) == 2 and value.startswith('${sec.data.'):
        channel_key = weechat.string_eval_expression(value, {}, {}, {})
        channel_data[option] = WeeSodiumChannel(channel_key)

    return weechat.WEECHAT_CONFIG_OPTION_SET_OK_CHANGED
Ejemplo n.º 36
0
def fish_secure_genkey(buffer):
    global fish_secure_cipher, fish_config_option

    newKey = blowcrypt_b64encode(urandom(32))

    # test to see if sec.conf decrypted
    weechat.command(buffer, "/secure set fish test")
    decrypted = weechat.string_eval_expression(
        "${sec.data.fish}", {}, {}, {}
    )

    if decrypted == "test":
        weechat.config_option_set(fish_config_option["key"],
                                  "${sec.data.fish}", 0)
        fish_secure_cipher = Blowfish(newKey)
        weechat.command(buffer, "/secure set fish %s" % newKey)
Ejemplo n.º 37
0
def grabnick_and_auth(servername, nick):
    global OPTIONS
    # get password for given server (evaluated)
    if int(version) >= 0x00040200:
        password = weechat.string_eval_expression(
            weechat.config_get_plugin('%s.password' % servername), {}, {}, {})
    else:
        password = weechat.config_get_plugin('%s.password' % servername)

    grabnick(servername, nick)  # get your nick back

    if password != '' and OPTIONS['nickserv'] != '':
        # command stored in "keepnick.nickserv" option
        t = Template(OPTIONS['nickserv'])
        run_msg = t.safe_substitute(server=servername, passwd=password)
        weechat.command('', run_msg)
Ejemplo n.º 38
0
def config_changed_cb(data, option, value):
    global slack_api_token, channels_always_marked_read, channels_not_on_current_server_color, colorize_nicks, slack_debug, debug_mode
    slack_api_token = w.config_get_plugin("slack_api_token")

    if slack_api_token.startswith('${sec.data'):
        slack_api_token = w.string_eval_expression(slack_api_token, {}, {}, {})

    channels_always_marked_read = [x.strip() for x in w.config_get_plugin("channels_always_marked_read").split(',')]
    channels_not_on_current_server_color = w.config_get_plugin("channels_not_on_current_server_color")
    if channels_not_on_current_server_color == "0":
        channels_not_on_current_server_color = False
    colorize_nicks = w.config_get_plugin('colorize_nicks') == "1"
    slack_debug = None
    debug_mode = w.config_get_plugin("debug_mode").lower()
    if debug_mode != '' or debug_mode != 'false':
        create_slack_debug_buffer()
    return w.WEECHAT_RC_OK
Ejemplo n.º 39
0
def send_push(title, body):
    global last_notification

    interval = w.config_get_plugin("min_notify_interval")
    if interval is not None and interval != "" and int(interval) != 0:
        interval = int(interval)

        earliest_notification = last_notification + int(interval)

        if last_notification is not None and time.time() <= earliest_notification:
            debug("Too soon since last notification, skipping")
            return w.WEECHAT_RC_OK

    last_notification = time.time()

    # check to see if the relay is connected, ignore if so
    check_relays = w.config_string_to_boolean(w.config_get_plugin('ignore_on_relay'))
    CONNECTED_RELAY = False
    if check_relays:
        infolist = w.infolist_get('relay', '', '')
        if infolist:
            while w.infolist_next(infolist):
                status = w.infolist_string(infolist, 'status_string')
                if status == 'connected':
                    CONNECTED_RELAY = True
                    break
            w.infolist_free(infolist)

    if CONNECTED_RELAY is True:
        # we have a relay conected, don't notify
        debug("Relay is connected, not sending push.")
        return w.WEECHAT_RC_OK

    debug("Sending push.  Title: [%s], body: [%s]" % (title, body))

    apikey = w.string_eval_expression(w.config_get_plugin("api_key"), {}, {}, {})
    apiurl = "https://%[email protected]/v2/pushes" % (apikey)
    timeout = 20000  # FIXME - actually use config
    if len(title) is not 0 or len(body) is not 0:
        deviceiden = w.config_get_plugin("device_iden")
        if deviceiden == "all":
            payload = urllib.urlencode({'type': 'note', 'title': title, 'body': body.encode('utf-8')})
        else:
            payload = urllib.urlencode({'type': 'note', 'title': title, 'body': body.encode('utf-8'), 'device_iden': deviceiden})
        w.hook_process_hashtable("url:" + apiurl, {"postfields": payload, "header": "1"}, timeout, "process_pushbullet_cb", "")
Ejemplo n.º 40
0
def show_notification(chan, nick, message):
    API_TOKEN = weechat.config_get_plugin("api_token")

    # decrypt the API token if it is stored as secured data
    if API_TOKEN.startswith("${sec."):
        API_TOKEN = weechat.string_eval_expression(API_TOKEN, {}, {}, {})

    if API_TOKEN != "":
        url = "https://irssinotifier.appspot.com/API/Message"
        postdata = urlencode({'apiToken' : API_TOKEN,
                              'nick'     : encrypt(nick),
                              'channel'  : encrypt(chan),
                              'message'  : encrypt(message),
                              'version'  : 13})
        version = weechat.info_get("version_number", "") or 0
        hook1 = weechat.hook_process_hashtable("url:" + url,
                                               {"postfields": postdata},
                                               2000, "", "")
Ejemplo n.º 41
0
def grabnick_and_auth(servername, nick):
    global OPTIONS
    # get password for given server (evaluated)
    if int(version) >= 0x00040200:
        password = weechat.string_eval_expression(
            weechat.config_get_plugin('%s.password' % servername), {},
            {}, {})
    else:
        password = weechat.config_get_plugin(
            '%s.password' % servername)

    grabnick(servername, nick)  # get your nick back

    if password != '' and OPTIONS['nickserv'] != '':
        # command stored in "keepnick.nickserv" option
        t = Template(OPTIONS['nickserv'])
        run_msg = t.safe_substitute(server=servername, passwd=password)
        weechat.command('', run_msg)
Ejemplo n.º 42
0
def fish_secure():
    global fish_secure_key, fish_secure_cipher

    fish_secure_key = weechat.config_string(fish_config_option["key"])

    # if blank, do nothing
    if fish_secure_key == "":
        return

    # if ${sec.data.fish}, check if sec.conf is decrypted
    # and decrypt
    elif fish_secure_key[:6] == "${sec.":
        decrypted = weechat.string_eval_expression(fish_secure_key, {}, {}, {})

        if decrypted:
            fish_secure_cipher = Blowfish(decrypted)
            fish_decrypt_keys()
            return

        else:
            global SCRIPT_NAME
            message = ("\n%s%sblowkey:%s unable to recover key from sec.conf\n"
                       "%s%sblowkey:%s fish.py %sNOT LOADED\n"
                       "%s%sblowkey:%s decrypt secured data first\n"
                       "%s%sblowkey:%s then reload fish.py\n\n") % (
                           weechat.prefix("error"), weechat.color("underline"),
                           weechat.color("reset"), weechat.prefix("error"),
                           weechat.color("underline"), weechat.color("reset"),
                           weechat.color("*red"), weechat.prefix("error"),
                           weechat.color("underline"), weechat.color("reset"),
                           weechat.prefix("error"), weechat.color("underline"),
                           weechat.color("reset"))

            weechat.prnt("", "%s" % message)
            weechat.command(weechat.current_buffer(),
                            "/wait 1ms /python unload %s" % SCRIPT_NAME)
            return

    # if key is neither ${sec.data.fish} or ""
    # encrypt/decrypt with user supplied, plain text key
    if fish_secure_key != "":
        fish_secure_cipher = Blowfish(fish_secure_key)
        fish_decrypt_keys()
        return
Ejemplo n.º 43
0
def generate_totp(server, period=30, buffer=""):
    print_debug('generate_totp(%s)' % server)
    seed = weechat.string_eval_expression("${sec.data.%s_seed}" % server, {}, {}, {})

    if not seed:
        sprint("No OATH-TOTP secret set, use: /uotp add %s <seed>" % server, buffer)
        return None

    if len(seed) == 40:  # Assume hex format
        seed = unhexlify(seed)
    else:
        seed = b32decode(seed.replace(" ", ""), True)

    t = pack(">Q", int(time() / period))
    _hmac = hmac.new(seed, t, sha1).digest()
    o = ord(_hmac[19]) & 15
    otp = (unpack(">I", _hmac[o:o+4])[0] & 0x7fffffff) % 1000000

    return '%06d' % otp
def generate_totp(server, period=30):
    print_debug('generate_totp(%s)' % server)
    seed = weechat.string_eval_expression("${sec.data.%s_seed}" % server, {}, {}, {})

    if seed is "":
        weechat.prnt("", "No OATH-TOTP secret set, use: /secure set %s_seed <secret>" % server)
        return None

    if len(seed) == 40:  # Assume hex format
        seed = unhexlify(seed)
    else:
        seed = b32decode(seed, True)

    t = pack(">Q", int(time() / period))
    _hmac = hmac.new(seed, t, sha1).digest()
    o = ord(_hmac[19]) & 15
    otp = (unpack(">I", _hmac[o:o+4])[0] & 0x7fffffff) % 1000000

    return '%06d' % otp
Ejemplo n.º 45
0
def styurl_line_cb(data, line):
    """
    Callback called when a line is displayed.
    This parses the message for any URLs and styles them according to
    styurl_settings["format"].
    """
    global styurl_settings

    # Don't style the line if it's not going to be displayed... duh
    if line["displayed"] != "1":
        return line

    tags = line["tags"].split(',')
    ignored_tags = styurl_settings["ignored_tags"]

    # Ignore specified message tags
    if ignored_tags:
        if any(tag in tags for tag in ignored_tags.split(',')):
            return line

    bufname = line["buffer_name"]
    ignored_buffers = styurl_settings["ignored_buffers"]

    # Ignore specified buffers
    if ignored_buffers and bufname in ignored_buffers.split(','):
        return line

    message = line["message"]

    # TODO: enforce presence of a properly-formatted color object at
    # styurl_settings["format"] (eval object would also be valid, if it eval'd
    # to a color)

    regex = re.compile(styurl_settings["regex"])
    url_style = w.string_eval_expression(styurl_settings["format"], {}, {}, {})
    reset = w.color("reset")

    # Search for URLs and surround them with the defined URL styling
    formatted = regex.sub(r"%s\1%s" % (url_style, reset), message)
    line["message"] = line["message"].replace(message, formatted)

    return line
Ejemplo n.º 46
0
def send_xmpp(message):
    if w.config_get_plugin('enable') != 'on':
        return
    jid = w.config_get_plugin('jid')
    jid_to = w.config_get_plugin('to')
    if not jid_to:
        jid_to = jid
    password = w.config_get_plugin('password')
    if re.search('sec.*data', password):
        password=w.string_eval_expression(password, {}, {}, {})

    xmpp = SendMsgBot(jid, password, jid_to, message)
    #xmpp.use_proxy = True
    #xmpp.proxy_config = {'host': 'localhost','port': 8123
    #                     'username': '******','password': '******',}
    if not xmpp.connect():
        w.prnt('', 'Unable to connect to XMPP server.')
        return
    xmpp.process(block=True)
    return
Ejemplo n.º 47
0
def encrypt(text):
    encryption_password = weechat.config_get_plugin("encryption_password")

    # decrypt the password if it is stored as secured data
    if encryption_password.startswith("${sec."):
        encryption_password = weechat.string_eval_expression(
            encryption_password, {}, {}, {})

    command = "openssl enc -aes-128-cbc -salt -base64 -md md5 -A -pass env:OpenSSLEncPW"
    opensslenv = os.environ.copy()
    opensslenv['OpenSSLEncPW'] = encryption_password
    output, errors = Popen(shlex.split(command),
                           stdin=PIPE,
                           stdout=PIPE,
                           stderr=PIPE,
                           env=opensslenv).communicate(text + " ")
    output = string.replace(output, "/", "_")
    output = string.replace(output, "+", "-")
    output = string.replace(output, "=", "")
    return output
Ejemplo n.º 48
0
def privmsg_cb(data, signal, signal_data):
    dict_in = {"message": signal_data}
    dict_out = weechat.info_get_hashtable("irc_message_parse", dict_in)
    if not weechat.info_get("irc_is_nick", dict_out["channel"]):
        return weechat.WEECHAT_RC_OK

    server = signal.split(",")[0]
    nick = dict_out["channel"]
    me = weechat.info_get("irc_nick", server)
    if nick != me:
        return weechat.WEECHAT_RC_OK

    if dict_out["nick"] != gribble_nick:
        return weechat.WEECHAT_RC_OK

    msg = dict_out["text"]
    m = re.match("^.*Get your encrypted OTP from (.*)$", msg)
    if m is None:
        return weechat.WEECHAT_RC_OK
    weechat.prnt(gribble_buffer, "Got OTP")
    otp_url = m.group(1)
    otp = urllib2.urlopen(otp_url).read()
    # the passphrase is stored encrypted in secure data
    expr = "${sec.data.%s}" % options["pass_key"]
    gpg_pass = weechat.string_eval_expression(expr, "", "", "")
    if gpg_pass == "":
        weechat.prnt(gribble_buffer, "no gpg pass found in secure data")
        return weechat.WEECHAT_RC_OK

    p = subprocess.Popen(
        ["gpg", "--batch", "--decrypt", "--passphrase", gpg_pass],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    out, err = p.communicate(otp)
    if err != "":
        weechat.prnt(gribble_buffer, "gpg output: " + err)
    if out != "":
        privmsg(server, gribble_nick, "everify %s" % out)

    return weechat.WEECHAT_RC_OK
Ejemplo n.º 49
0
def privmsg_cb(data, signal, signal_data):
    dict_in = {"message": signal_data}
    dict_out = weechat.info_get_hashtable("irc_message_parse", dict_in)
    if not weechat.info_get("irc_is_nick", dict_out["channel"]):
        return weechat.WEECHAT_RC_OK

    server = signal.split(",")[0]
    nick = dict_out["channel"]
    me = weechat.info_get("irc_nick", server)
    if nick != me:
        return weechat.WEECHAT_RC_OK

    if dict_out["nick"] != gribble_nick:
        return weechat.WEECHAT_RC_OK

    msg = dict_out["text"]
    m = re.match("^.*Get your encrypted OTP from (.*)$", msg)
    if m is None:
        return weechat.WEECHAT_RC_OK
    weechat.prnt(gribble_buffer, "Got OTP")
    otp_url = m.group(1)
    otp = urllib2.urlopen(otp_url).read()
    # the passphrase is stored encrypted in secure data
    expr = "${sec.data.%s}" % options["pass_key"]
    gpg_pass = weechat.string_eval_expression(expr, "", "", "")
    if gpg_pass == "":
        weechat.prnt(gribble_buffer, "no gpg pass found in secure data")
        return weechat.WEECHAT_RC_OK

    p = subprocess.Popen(["gpg", "--batch", "--decrypt", "--passphrase", gpg_pass],
            stdin = subprocess.PIPE,
            stdout = subprocess.PIPE,
            stderr = subprocess.PIPE)
    out, err = p.communicate(otp)
    if err != "":
        weechat.prnt(gribble_buffer, "gpg output: " + err)
    if out != "":
        privmsg(server, gribble_nick, "everify %s" % out)

    return weechat.WEECHAT_RC_OK
Ejemplo n.º 50
0
def timer_cb(data, remaining_calls):
    global indent
    current_time = int(time.time())
    interval = int(weechat.config_get_plugin('modulo_interval')) * 60
    if (current_time % interval) == 0:
        timestamp = clock(current_time)
        clocked = []
        infolist = weechat.infolist_get('window', '', '')
        if infolist:
            prefix = int(
                weechat.string_eval_expression(
                    "${weechat.look.prefix_align_min}", {}, {}, {}))
            if weechat.config_get_plugin('offset_prefix') == '0':
                offset = (prefix + 3) / 2  # including prefix separator
            else:
                offset = 0
            while weechat.infolist_next(infolist):
                if weechat.config_get_plugin('center') == '0':
                    indent = 0
                else:
                    # centering = (window width - prefix width - prefix separator - buffertape date) / 2 - offset - rounding adjustment
                    window = weechat.infolist_pointer(infolist, 'pointer')
                    indent = (weechat.window_get_integer(window, 'win_width') -
                              prefix - 2 - 11) / 2 - offset - 1
                buffer = weechat.window_get_pointer(window, 'buffer')
                if not buffer in clocked:
                    clocked.append(buffer)
                    weechat.prnt(buffer, ' ' * indent + timestamp)
        infolist = weechat.infolist_get('buffer', '', '')
        if infolist:
            while weechat.infolist_next(infolist):
                buffer = weechat.infolist_pointer(infolist, 'pointer')
                if not buffer in clocked:
                    clocked.append(buffer)
                    weechat.prnt(buffer, timestamp)
            weechat.infolist_free(infolist)
        del clocked
    return weechat.WEECHAT_RC_OK
Ejemplo n.º 51
0
def timer_cb(data, remaining_calls):
    global indent
    current_time = int(time.time())
    interval = int(weechat.config_get_plugin('modulo_interval')) * 60
    if (current_time % interval) == 0:
        infolist = weechat.infolist_get("buffer", "", "")
        if infolist:
            # set static width, assumes balanced window widths
            if indent < 0:
                if weechat.config_get_plugin('center') == '0':
                    indent = 0
                else:
                    # centering = (window width - prefix width - (vertical separator + date)) / 2 - rounding adjustment
                    indent = (weechat.window_get_integer(
                        weechat.current_window(), "win_width") - int(
                            weechat.string_eval_expression(
                                "${weechat.look.prefix_align_min}", {}, {},
                                {})) - 14) / 2 - 1
            while weechat.infolist_next(infolist):
                buffer = weechat.infolist_pointer(infolist, 'pointer')
                prnt_timestamp(buffer, current_time, indent)
            weechat.infolist_free(infolist)
    return weechat.WEECHAT_RC_OK
Ejemplo n.º 52
0
def fish_secure():
    global fish_secure_key, fish_secure_cipher

    fish_secure_key = weechat.config_string(fish_config_option["key"])

    # if blank, do nothing
    if fish_secure_key == "":
        fish_success()
        return

    # if ${sec.data.fish}, check if sec.conf is decrypted
    # and decrypt
    elif fish_secure_key[:6] == "${sec.":
        decrypted = weechat.string_eval_expression(
            fish_secure_key, {}, {}, {}
        )

        if decrypted:
            fish_secure_cipher = Blowfish(decrypted)
            fish_decrypt_keys()
            fish_success()
            return

        else:
            global SCRIPT_NAME
            fish_secure_error()
            weechat.command(weechat.current_buffer(),
                            "/wait 1ms /python unload %s" % SCRIPT_NAME)
            return

    # if key is neither ${sec.data.fish} or ""
    # encrypt/decrypt with user supplied, plain text key
    if fish_secure_key != "":
        fish_secure_cipher = Blowfish(fish_secure_key)
        fish_decrypt_keys()
        fish_success()
        return
Ejemplo n.º 53
0
def redirect_isonhandler(data, signal, hashtable):
    if hashtable['output'] == '':
        return weechat.WEECHAT_RC_OK

    # ISON_nicks contains nicks that are already online on server (separated with space)
    message,ISON_nicks = hashtable['output'].split(':')[1:]
    ISON_nicks = [nick.lower() for nick in ISON_nicks.split()]

    for nick in server_nicks(hashtable['server']):
        mynick = weechat.info_get('irc_nick',hashtable['server'])
        if nick.lower() == mynick.lower():
            return weechat.WEECHAT_RC_OK
        elif nick.lower() not in ISON_nicks and nick != '':
            if int(version) >= 0x00040200:
                password = weechat.string_eval_expression(weechat.config_get_plugin('%s.password' % hashtable['server']),{},{},{})
            else:
                password = weechat.config_get_plugin('%s.password' % hashtable['server'])   # get password for given server

            grabnick(hashtable['server'], nick)                                         # get your nick back
            if password != '' and OPTIONS['nickserv'] != '':
                t = Template(OPTIONS['nickserv'])
                run_msg = t.safe_substitute(server=hashtable['server'], passwd=password)
                weechat.command('',run_msg)
    return weechat.WEECHAT_RC_OK
Ejemplo n.º 54
0
def configured_servers():
    """ Return a lost of servers with an existing seed. """
    serverlist = get_irc_servers()
    return [s for s in serverlist if weechat.string_eval_expression("${sec.data.%s_seed}" % s, {}, {}, {})]
Ejemplo n.º 55
0
SCRIPT_AUTHOR   = "nils_2 <*****@*****.**>"
SCRIPT_VERSION  = "0.1"
SCRIPT_LICENSE  = "GPL"
SCRIPT_DESC     = "script description for weechat"

OPTIONS         = {'option_name'        : ('value','help text for option'),
                   'password'           : ('${sec.data.my_password}','see /help secure'),
                  }

# eval_expression():  to match ${color:nn} tags
regex_color=re.compile('\$\{color:([^\{\}]+)\}')

# ==========================[ eval_expression() ]========================
# this is for WeeChat >= 0.4.2
# get value from your 'password' option and return the encoded text
password = weechat.string_eval_expression(weechat.config_get_plugin('password'),{},{},{})

# this is how to easily use weechat colors in your script
text = substitute_colors('my text ${color:yellow}yellow${color:default} colored.')
def substitute_colors(text):
    if int(version) >= 0x00040200:
        return weechat.string_eval_expression(text,{},{},{})
    # substitute colors in output
    return re.sub(regex_color, lambda match: weechat.color(match.group(1)), text)

# ================================[ item ]===============================
def bar_item_cb (data, item, window):
    # check for root input bar!
    if not window:
        window = weechat.current_window()
Ejemplo n.º 56
0
# register plugin
if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "", "UTF-8"):
    buffer = weechat.buffer_new("weeText", "gvOut", "", "buffer_close_cb", "")
    weechat_dir = weechat.info_get("weechat_dir","")
    key_dir = weechat.config_get_plugin("key_dir")
    weechat.bar_item_new('encryption', 'encryption_statusbar', '')
    for option, default_value in script_options.iteritems():
        if not weechat.config_is_set_plugin(option):
            weechat.config_set_plugin(option, default_value)

    # get email/passwd and pass to other script
    email=weechat.config_get_plugin('email')
    passwd = weechat.config_get_plugin('passwd')
    if re.search('sec.*data', passwd):
        passwd=weechat.string_eval_expression(passwd, {}, {}, {})

    # write the helper files
    with open(weechat_dir + '/python/wtrecv.py', 'w') as f:
        f.write("""#!/usr/bin/env python2

import sys
import cPickle
import time
import re
import os
import glob
from googlevoice import Voice
from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup, SoupStrainer

user_path = os.path.expanduser('~')
Ejemplo n.º 57
0
def timer_cb(data, remaining_calls):
    global indent
    current_time = int(time.time())
    interval = int(weechat.config_get_plugin('modulo_interval')) * 60
    if (current_time % interval) == 0:
        infolist = weechat.infolist_get("buffer", "", "")
        if infolist:
            # set static width, assumes balanced window widths
            if indent < 0:
                if weechat.config_get_plugin('center') == '0':
                    indent = 0
                else:
                    # centering = (window width - prefix width - (vertical separator + date)) / 2 - rounding adjustment
                    indent = (weechat.window_get_integer(weechat.current_window (), "win_width") - int(weechat.string_eval_expression("${weechat.look.prefix_align_min}", {}, {}, {})) - 14) / 2 - 1
            while weechat.infolist_next(infolist):
                buffer = weechat.infolist_pointer(infolist, 'pointer')
                prnt_timestamp(buffer, current_time, indent)
            weechat.infolist_free(infolist)
    return weechat.WEECHAT_RC_OK
Ejemplo n.º 58
0
def substitute_colors(text):
    if int(version) >= 0x00040200:
        return weechat.string_eval_expression(text, {}, {}, {})
    # substitute colors in output
    return re.sub(regex_color, lambda match: weechat.color(match.group(1)), text)