<commit_before>#!/usr/bin/env python2

import weechat
import subprocess
from os import path
import json

weechat.register("weecrypt", "shak-mar", "0.1", "None",
                 "asymmetric encryption for weechat using gpg", "", "")

channel_whitelist = []
gpg_identifiers = {}
max_length = 300
buffers = {}
config_path = "~/.weecrypt.json"

# Load the configuration
if path.isfile(path.expanduser(config_path)):
    with open(path.expanduser(config_path)) as f:
        config = json.loads(f.read())
        channel_whitelist = config["channels"]
        gpg_identifiers = config["gpg_identifiers"]

else:
    weechat.prnt("",
                 "Error: Cant find configuration file at: %s." % config_path)


# Retrieve your own nick
def my_nick(server_name):
    return weechat.info_get("irc_nick", server_name)


# Returns all nicks in a channel, except your own
def other_nicks(channel_name, server_name):
    nicks = []
    infolist = weechat.infolist_get("irc_nick", "",
                                    server_name + "," + channel_name)
    rc = weechat.infolist_next(infolist)
    while rc:
        nick = weechat.infolist_string(infolist, "name")
        if nick != my_nick(server_name):
            nicks.append(nick)
        rc = weechat.infolist_next(infolist)

    return nicks


# Encrypt a message for all possible recipients
def encrypt(message, parsed):
    # Set the correct to_nicks
    to_nicks = []
    if parsed["channel"].startswith("#"):
        to_nicks = other_nicks(parsed["channel"], parsed["server"])
    else:
        to_nicks = [parsed["channel"]]

    # Assemble the command
    command = ["gpg2", "--armor", "--encrypt","--batch","--no-tty"]
    for nick in to_nicks:
        if nick in gpg_identifiers:
            command.extend(["--recipient", gpg_identifiers[nick]])

    # Only encrypt if there are receipients
    if "--recipient" in command:
        # Run the command and collect its output
        p = subprocess.Popen(command,
                             stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)

        encoded, err = p.communicate(message)

        if p.returncode == 0:
            encoded = encoded.decode().strip()
            return [encoded, True]

        else:
            err = err.decode().strip()
            return [err, False]

    return ["", False]


# Decrypt a received message
def decrypt(message):
    p = subprocess.Popen(["gpg2", "--armor", "--decrypt","--batch","--no-tty"],
                         stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)<commit_msg>Remove bulk from the messages<commit_after>#!/usr/bin/env python2

import weechat
import subprocess
from os import path
import json

weechat.register("weecrypt", "shak-mar", "0.1", "None",
                 "asymmetric encryption for weechat using gpg", "", "")

channel_whitelist = []
gpg_identifiers = {}
max_length = 300
buffers = {}
config_path = "~/.weecrypt.json"

# Load the configuration
if path.isfile(path.expanduser(config_path)):
    with open(path.expanduser(config_path)) as f:
        config = json.loads(f.read())
        channel_whitelist = config["channels"]
        gpg_identifiers = config["gpg_identifiers"]

else:
    weechat.prnt("",
                 "Error: Cant find configuration file at: %s." % config_path)


# Retrieve your own nick
def my_nick(server_name):
    return weechat.info_get("irc_nick", server_name)


# Returns all nicks in a channel, except your own
def other_nicks(channel_name, server_name):
    nicks = []
    infolist = weechat.infolist_get("irc_nick", "",
                                    server_name + "," + channel_name)
    rc = weechat.infolist_next(infolist)
    while rc:
        nick = weechat.infolist_string(infolist, "name")
        if nick != my_nick(server_name):
            nicks.append(nick)
        rc = weechat.infolist_next(infolist)

    return nicks

bulk_begin = "-----BEGIN PGP MESSAGE-----\nVersion: GnuPG v2\n\n"
bulk_end = "-----END PGP MESSAGE-----"

# Encrypt a message for all possible recipients
def encrypt(message, parsed):
    # Set the correct to_nicks
    to_nicks = []
    if parsed["channel"].startswith("#"):
        to_nicks = other_nicks(parsed["channel"], parsed["server"])
    else:
        to_nicks = [parsed["channel"]]

    # Assemble the command
    command = ["gpg2", "--armor", "--encrypt","--batch","--no-tty"]
    for nick in to_nicks:
        if nick in gpg_identifiers:
            command.extend(["--recipient", gpg_identifiers[nick]])

    # Only encrypt if there are receipients
    if "--recipient" in command:
        # Run the command and collect its output
        p = subprocess.Popen(command,
                             stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)

        encoded, err = p.communicate(message)

        if p.returncode == 0:
            encoded = encoded.decode().strip()
            encoded = encoded[len(bulk_begin):][:-len(bulk_end)]
            return [encoded, True]

        else:
            err = err.decode().strip()
            return [err, False]

    return ["", False]


# Decrypt a received message
def decrypt(message):
    message = bulk_begin + message + bulk_end
    p = subprocess.Popen(["gpg2", "--armor", "--decrypt","--batch","--no-tty"],
                         stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
{'fraction_non_alphanumeric': 0.12854545454545455, 'fraction_numerical': 0.0034545454545454545, 'mean_word_length': 2.501591343093571, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2164771', 'n_tokens_mistral': 1754, 'n_tokens_neox': 1702, 'n_words': 397}