Exemple #1
0
def pytest_report_header(config, startdir):
    summary = []

    t = tempfile.mktemp()
    m = MonkeyPatch()
    try:
        m.setattr(sys.stdout, "write", lambda x: len(x))
        ac = Account(t)
        info = ac.get_info()
        ac.shutdown()
    finally:
        m.undo()
        os.remove(t)
    summary.extend([
        'Deltachat core={} sqlite={}'.format(
            info['deltachat_core_version'],
            info['sqlite_version'],
        )
    ])

    cfg = config.option.liveconfig
    if cfg:
        if "#" in cfg:
            url, token = cfg.split("#", 1)
            summary.append(
                'Liveconfig provider: {}#<token ommitted>'.format(url))
        else:
            summary.append('Liveconfig file: {}'.format(cfg))
    return summary
def pytest_report_header(config, startdir):
    summary = []

    t = tempfile.mktemp()
    try:
        ac = Account(t, eventlogging=False)
        info = ac.get_info()
        ac.shutdown()
    finally:
        os.remove(t)
    summary.extend([
        'Deltachat core={} sqlite={}'.format(
            info['deltachat_core_version'],
            info['sqlite_version'],
        )
    ])

    cfg = config.option.liveconfig
    if cfg:
        if "#" in cfg:
            url, token = cfg.split("#", 1)
            summary.append(
                'Liveconfig provider: {}#<token ommitted>'.format(url))
        else:
            summary.append('Liveconfig file: {}'.format(cfg))
    return summary
Exemple #3
0
def pytest_report_header(config, startdir):
    t = tempfile.mktemp()
    try:
        ac = Account(t)
        info = ac.get_info()
        del ac
    finally:
        os.remove(t)
    return "Deltachat core={} sqlite={}".format(
        info['deltachat_core_version'],
        info['sqlite_version'],
    )
Exemple #4
0
 def get_online_configuring_account(self):
     if not fn:
         pytest.skip("specify a --liveconfig file to run tests with real accounts")
     self.live_count += 1
     configdict = self.configlist.pop(0)
     tmpdb = tmpdir.join("livedb%d" % self.live_count)
     ac = Account(tmpdb.strpath, logid="ac{}".format(self.live_count))
     ac._evlogger.init_time = self.init_time
     ac._evlogger.set_timeout(30)
     ac.configure(**configdict)
     ac.start_threads()
     self._finalizers.append(ac.stop_threads)
     return ac
Exemple #5
0
def pytest_report_header(config, startdir):
    t = tempfile.mktemp()
    try:
        ac = Account(t)
        info = ac.get_info()
        del ac
    finally:
        os.remove(t)
    return "Deltachat core={} rpgp={} openssl={} sqlite={}".format(
        info["deltachat_core_version"],
        info["rpgp_enabled"],
        info['openssl_version'],
        info['sqlite_version'],
    )
Exemple #6
0
 def get_unconfigured_account(self):
     self.offline_count += 1
     tmpdb = tmpdir.join("offlinedb%d" % self.offline_count)
     ac = Account(tmpdb.strpath, logid="ac{}".format(self.offline_count))
     ac._evlogger.init_time = self.init_time
     ac._evlogger.set_timeout(2)
     return ac
Exemple #7
0
 def __init__(self, email=None, password=None, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.waiting = False
     db = join(gettempdir(), "HiveMindDeltaChatBridge_" + str(email))
     self.account = Account(db)
     self.email = email
     self.pswd = password
     self.allowed_emails = []  # if empty allow all
     if not self.account.is_configured():
         self.account.set_config("addr", self.email)
         self.account.set_config("mail_pw", self.pswd)
         self.account.set_config("mvbox_move", "0")
         self.account.set_config("mvbox_watch", "0")
         self.account.set_config("sentbox_watch", "0")
         configtracker = self.account.configure()
         configtracker.wait_finish()
     # map email addresses to deltachat objects
     self.addr2chat = {}
Exemple #8
0
def make_bot_from_args(args, plugin_manager, account=None):
    basedir = os.path.abspath(os.path.expanduser(args.basedir))
    if not os.path.exists(basedir):
        os.makedirs(basedir)

    if account is None:
        db_path = os.path.join(basedir, "account.db")
        account = Account(db_path, "deltabot/{}".format(sys.platform))

    logger = plugin_manager.hook.deltabot_get_logger(args=args)
    return DeltaBot(account, logger, plugin_manager=plugin_manager, args=args)
Exemple #9
0
 def clone_online_account(self, account):
     self.live_count += 1
     tmpdb = tmpdir.join("livedb%d" % self.live_count)
     ac = Account(tmpdb.strpath, logid="ac{}".format(self.live_count))
     ac._evlogger.init_time = self.init_time
     ac._evlogger.set_timeout(30)
     ac.configure(addr=account.get_config("addr"), mail_pw=account.get_config("mail_pw"))
     ac.start_threads()
     self._finalizers.append(lambda: ac.stop_threads(wait=False))
     return ac
Exemple #10
0
 def get_online_configuring_account(self):
     if not fn:
         pytest.skip("specify a --liveconfig file to run tests with real accounts")
     self.live_count += 1
     configdict = self.configlist.pop(0)
     tmpdb = tmpdir.join("livedb%d" % self.live_count)
     ac = Account(tmpdb.strpath, logid="ac{}".format(self.live_count))
     ac._evlogger.init_time = self.init_time
     ac._evlogger.set_timeout(30)
     ac.configure(**configdict)
     ac.start_threads()
     self._finalizers.append(lambda: ac.stop_threads(wait=False))
     return ac
Exemple #11
0
 def get_online_configuring_account(self):
     if not session_liveconfig:
         pytest.skip("specify DCC_PY_LIVECONFIG or --liveconfig")
     configdict = session_liveconfig.get(self.live_count)
     self.live_count += 1
     if "e2ee_enabled" not in configdict:
         configdict["e2ee_enabled"] = "1"
     tmpdb = tmpdir.join("livedb%d" % self.live_count)
     ac = Account(tmpdb.strpath, logid="ac{}".format(self.live_count))
     ac._evlogger.init_time = self.init_time
     ac._evlogger.set_timeout(30)
     ac.configure(**configdict)
     ac.start_threads()
     self._finalizers.append(ac.shutdown)
     return ac
 def make_account(self, path, logid):
     ac = Account(path, logid=logid)
     self._finalizers.append(ac.shutdown)
     return ac
Exemple #13
0
def test_wrong_db(tmpdir):
    tmpdir.join("hello.db").write("123")
    with pytest.raises(ValueError):
        Account(db_path=tmpdir.strpath)
 def __init__(self, account: Account) -> None:
     self.account = account
     self.logid = account.get_config("displayname") or id(account)
     self._idling = False
     self.connect()
Exemple #15
0
def main() -> None:
    sys.argv[0] = "curseddelta"
    argv = sys.argv
    app_path = os.path.join(os.path.expanduser("~"), ".curseddelta")
    if not os.path.exists(app_path):
        os.makedirs(app_path)
    cfg = get_configuration()

    parser = argparse.ArgumentParser(prog=argv[0])
    parser.add_argument(
        "--db",
        action="store",
        help="database file",
        default=cfg["general"]["account_path"],
    )
    parser.add_argument(
        "--show-ffi", action="store_true", help="show low level ffi events"
    )
    parser.add_argument("--email", action="store", help="email address")
    parser.add_argument("--password", action="store", help="password")
    parser.add_argument("--set-conf", action="store", help="set config option", nargs=2)
    parser.add_argument("--get-conf", action="store", help="get config option")
    parser.add_argument(
        "--port",
        action="store",
        help="port to listen for oauth2 callback",
        type=int,
        default="8383",
    )

    args = parser.parse_args(argv[1:])

    ac = Account(os.path.expanduser(args.db))

    if args.get_conf:
        print(ac.get_config(args.get_conf))
        return

    if args.show_ffi:
        log = events.FFIEventLogger(ac, "CursedDelta")
        ac.add_account_plugin(log)

    if not ac.is_configured():
        assert (
            args.email
        ), "you must specify --email once to configure this database/account"
        ac.set_config("addr", args.email)

        if not args.password and is_oauth2(ac, args.email):
            authz_code = get_authz_code(ac, args.email, args.port)

            ac.set_config("mail_pw", authz_code)

            flags = ac.get_config("server_flags")
            flags = int(flags) if flags else 0
            flags |= deltachat.const.DC_LP_AUTH_OAUTH2
            ac.set_config("server_flags", str(flags))
        else:
            assert (
                args.password
            ), "you must specify --password once to configure this database/account"
            ac.set_config("mail_pw", args.password)

        with ac.temp_plugin(ConfigureTracker(ac)) as tracker:
            ac.configure()
            tracker.wait_finish()

    if args.set_conf:
        ac.set_config(*args.set_conf)

    account = AccountPlugin(ac)
    ac.add_account_plugin(account)

    ac.start_io()

    keymap = get_keymap()
    theme = get_theme()
    CursedDelta(cfg, keymap, theme, APP_NAME, account)
    ac.shutdown()
 def test_wrong_db(self, tmpdir):
     p = tmpdir.join("hello.db")
     p.write("123")
     with pytest.raises(ValueError):
         Account(p.strpath)
Exemple #17
0
class JarbasDeltaChatBridge(HiveMindTerminal):
    protocol = JarbasDeltaChatBridgeProtocol
    platform = "JarbasDeltaChatBridgeV0.1"

    def __init__(self, email=None, password=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.waiting = False
        db = join(gettempdir(), "HiveMindDeltaChatBridge_" + str(email))
        self.account = Account(db)
        self.email = email
        self.pswd = password
        self.allowed_emails = []  # if empty allow all
        if not self.account.is_configured():
            self.account.set_config("addr", self.email)
            self.account.set_config("mail_pw", self.pswd)
            self.account.set_config("mvbox_move", "0")
            self.account.set_config("mvbox_watch", "0")
            self.account.set_config("sentbox_watch", "0")
            configtracker = self.account.configure()
            configtracker.wait_finish()
        # map email addresses to deltachat objects
        self.addr2chat = {}

    # deltachat events
    @account_hookimpl
    def ac_incoming_message(self, message):
        print("process_incoming message", message)
        if message.is_system_message():
            return  # TODO send hivemind event?

        # check allowed emails
        addr = message.get_sender_contact().addr

        if not self.allowed_emails or addr in self.allowed_emails:
            # accept the chat
            message.create_chat()
        else:
            return  # TODO send hivemind event?

        self.addr2chat[addr] = message.chat
        utterance = message.text
        msg = {
            "data": {
                "utterances": [utterance],
                "lang": "en-us"
            },
            "type": "recognizer_loop:utterance",
            "context": {
                "source": self.client.peer,
                "destination": "hive_mind",
                "deltachat_user": addr,
                "platform": self.platform
            }
        }
        self.send_to_hivemind_bus(msg)

    # hivemind bridge functionality
    def speak(self, utterance, addr):
        self.addr2chat[addr].send_text(utterance)

    def run_deltachat(self):
        self.account.add_account_plugin(self)
        # start IO threads and configure if necessary
        self.account.start_io()
        print("Running deltachat bridge for: " +
              self.account.get_config("addr"))
        self.account.wait_shutdown()

    # parsed hivemind protocol messages
    def handle_incoming_mycroft(self, message):
        assert isinstance(message, Message)
        addr = message.context.get("deltachat_user")
        if not addr:
            return
        if message.msg_type == "speak":
            utterance = message.data["utterance"]
            self.speak(utterance, addr)
        elif message.msg_type == "hive.complete_intent_failure":
            LOG.error("complete intent failure")
            self.speak('I don\'t know how to answer that', addr)

    # hivemind websocket
    def clientConnectionLost(self, connector, reason):
        super().clientConnectionLost(connector, reason)
        # if set to auto reconnect the hivemind connection is reestablished,
        # otherwise we want to shutdown deltachat
        if not self.auto_reconnect:
            self.account.shutdown()