Exemple #1
0
    def __init__(self):
        """Init the window"""
        self.root = Tk()
        self.settings = Settings()
        self.root.title(self.settings.title)
        self.root.geometry(self.settings.geometry)
        self._set_background()
        self.root.iconbitmap(self.settings.icon)
        self.path = ""
        self.password = ""

        self.callbacks = Callbacks()

        # init entry text
        self.pass_label = Label(self.root, text="Password: "******"*",
                              width=self.settings.entry_width,
                              border=self.settings.entry_border)
        self.password.grid(row=1, column=2, columnspan=2)

        # init entry local path
        self.path_text = Label(self.root, text="Local path: ")
        self.path_text.grid(row=2, column=0)
        self.path_label = Label(
            self.root,
            text="Please click load file button to select a file",
            width=self.settings.entry_width + 4,
            border=self.settings.entry_border)
        self.path_label.grid(row=2, column=2, columnspan=2)

        self.__buttons_init()
Exemple #2
0
    def __init__(self):
        """Init the window"""
        self.root = Tk()

        self.settings = Settings()
        self.root.title(self.settings.title)
        self.root.geometry(self.settings.geometry)
        self._set_background()
        self.root.iconbitmap(self.settings.icon)

        self.callbacks = Callbacks()

        # init entry text
        self.password = Entry(
            self.root, show="*", width=self.settings.entry_width, border=self.settings.entry_border)
        self.password.grid(row=1, column=1)
        # self.password.pack()

        # init buttons
        self.encryptionButton = Button(self.root, text="Encrypt",
                                       padx=self.settings.padx, pady=self.settings.pady, command=lambda: self.callbacks.encrypt_button(self.password.get()))
        self.encryptionButton.grid(row=2, column=0)

        self.decryptionButton = Button(self.root, text="Decrypt",
                                       padx=self.settings.padx, pady=self.settings.pady, command=lambda: self.callbacks.decrypt_button(self.password.get()))
        self.decryptionButton.grid(row=2, column=2)

        self.decryptionButton = Button(self.root, text="Open file",
                                       padx=self.settings.padx, pady=self.settings.pady, command=self.callbacks.open_file)
        self.decryptionButton.grid(row=2, column=1)
Exemple #3
0
	def __init__ (self, beforeStart=None):
		self._resolvedCallbacks = Callbacks(once=True, memory=True)
		self._rejectedCallbacks = Callbacks(once=True, memory=True)
		self._progressCallbacks = Callbacks(memory=True)
		self._states = ['pending','rejected','resolved']
		self._state = self._states[0]
		if beforeStart is not None:
			beforeStart(self)
Exemple #4
0
async def main():
    # Read config file
    config = Config("config.yaml")

    # Configuration options for the AsyncClient
    nio_client_config = AsyncClientConfig(
        max_limit_exceeded=0,
        max_timeouts=0,
        store_sync_tokens=True,
    )

    # Initialize the matrix client
    nio_client = AsyncClient(
        config.homeserver_url,
        config.user_id,
        device_id=config.device_id,
        config=nio_client_config,
        store_path="/home/brendan/Documents/matrix-monzo-next/nio_store",
    )

    # Initialise the monzo client
    monzo_client = Monzo(config.monzo_access_token)

    await nio_client.login(config.password, "monzo_bot")

    # Set up event callbacks
    callbacks = Callbacks(config, nio_client, monzo_client)
    nio_client.add_event_callback(callbacks.message, (RoomMessageText, ))
    nio_client.add_event_callback(callbacks.invite, (InviteEvent, ))

    # First do a sync with full_state = true to retrieve the state of the room.
    await nio_client.sync(full_state=True)

    await nio_client.sync_forever(30000)
Exemple #5
0
async def main():
    # Read config file
    config = Config("config.yaml")

    # Configure the database
    store = Storage(config.database_filepath)

    # Configuration options for the AsyncClient
    client_config = AsyncClientConfig(
        max_limit_exceeded=0,
        max_timeouts=0,
    )

    # Initialize the matrix client
    client = AsyncClient(
        config.homeserver_url,
        config.user_id,
        device_id=config.device_id,
        config=client_config,
    )

    logger.debug("Connected to Matrix!")

    # Assign an access token to the bot instead of logging in and creating a new device
    client.access_token = config.access_token

    # Set up event callbacks
    callbacks = Callbacks(client, store, config)
    client.add_event_callback(callbacks.message, (RoomMessageText, ))
    client.add_event_callback(callbacks.invite, (InviteEvent, ))

    # Retrieve the last sync token if it exists
    token = store.get_sync_token()

    # Sync loop
    while True:
        # Sync with the server
        sync_response = await client.sync(timeout=30000,
                                          full_state=True,
                                          since=token)

        # Check if the sync had an error
        if type(sync_response) == SyncError:
            logger.warning("Error in client sync: %s", sync_response.message)
            continue

        # Save the latest sync token
        token = sync_response.next_batch
        if token:
            store.save_sync_token(token)
Exemple #6
0
class Deferred:

	def __init__ (self, beforeStart=None):
		self._resolvedCallbacks = Callbacks(once=True, memory=True)
		self._rejectedCallbacks = Callbacks(once=True, memory=True)
		self._progressCallbacks = Callbacks(memory=True)
		self._states = ['pending','rejected','resolved']
		self._state = self._states[0]
		if beforeStart is not None:
			beforeStart(self)

	def reject (self, *args, **kwargs):
		if self.pending():
			self._rejectedCallbacks.fire(*args, **kwargs)
		return self

	def resolve (self, *args, **kwargs):
		if self.pending():
			self._resolvedCallbacks.fire(*args, **kwargs)
		return self

	def notify (self, *args, **kwargs):
		if self.pending():
			self._progressCallbacks.fire(*args, **kwargs)
		return self

	def _addListener (self, callbacks, fn, *args):
		for arg in args:
			if isfunction(arg):
				callbacks.add(arg)
			elif isinstance(arg, Deferred):
				callbacks.add(lambda *args, **kwargs:getattr(arg, fn)(*args,**kwargs))
		return self

	def progress (self, *args):
		return self._addListener(self._progressCallbacks, 'notify', *args)

	def done (self, *args):
		return self._addListener(self._resolvedCallbacks, 'resolve', *args)

	def fail (self, *args):
		return self._addListener(self._rejectedCallbacks, 'reject', *args)

	def always (self, *args):
		return self.done(*args).fail(*args)

	def pending (self):
		return self._state is self._states[0]

	def rejected (self):
		return self._state is self._states[1]

	def resolved (self):
		return self._state is self._states[2]
Exemple #7
0
def create_callbacks(name, dumps):
    log_dir = Path(dumps['path']) / dumps['logs'] / name
    save_dir = Path(dumps['path']) / dumps['weights'] / name
    callbacks = Callbacks(
        [
            Logger(log_dir),
            CheckpointSaver(
                metric_name=dumps['metric_name'],
                save_dir=save_dir,
                save_name='epoch_{epoch}.pth',
                num_checkpoints=4,
                mode='max'
            ),
            TensorBoard(str(log_dir)),
            FreezerCallback()
        ]
    )
    return callbacks
Exemple #8
0
async def main():
    # Read config file

    # A different config file path can be specified as the first command line argument
    if len(sys.argv) > 1:
        config_filepath = sys.argv[1]
    else:
        config_filepath = "config.yaml"
    config = Config(config_filepath)

    # Configure the database
    store = Storage(config.database_filepath)

    # Configuration options for the AsyncClient
    client_config = AsyncClientConfig(
        max_limit_exceeded=0,
        max_timeouts=0,
        store_sync_tokens=True,
        encryption_enabled=True,
    )

    # Initialize the matrix client
    client = AsyncClient(
        config.homeserver_url,
        config.user_id,
        device_id=config.device_id,
        store_path=config.store_filepath,
        config=client_config,
    )

    # Set up event callbacks
    callbacks = Callbacks(client, store, config)
    client.add_event_callback(callbacks.message, (RoomMessageText, ))
    client.add_event_callback(callbacks.invite, (InviteMemberEvent, ))

    # Keep trying to reconnect on failure (with some time in-between)
    while True:
        try:
            # Try to login with the configured username/password
            try:
                login_response = await client.login(
                    password=config.user_password,
                    device_name=config.device_name,
                )

                # Check if login failed
                if type(login_response) == LoginError:
                    logger.error(f"Failed to login: %s",
                                 login_response.message)
                    return False
            except LocalProtocolError as e:
                # There's an edge case here where the user hasn't installed the correct C
                # dependencies. In that case, a LocalProtocolError is raised on login.
                logger.fatal(
                    "Failed to login. Have you installed the correct dependencies? "
                    "https://github.com/poljar/matrix-nio#installation "
                    "Error: %s", e)
                return False

            # Login succeeded!

            # Sync encryption keys with the server
            # Required for participating in encrypted rooms
            if client.should_upload_keys:
                await client.keys_upload()

            logger.info(f"Logged in as {config.user_id}")
            await client.sync_forever(timeout=30000, full_state=True)

        except (ClientConnectionError, ServerDisconnectedError):
            logger.warning(
                "Unable to connect to homeserver, retrying in 15s...")

            # Sleep so we don't bombard the server with login requests
            sleep(15)
        finally:
            # Make sure to close the client connection on disconnect
            await client.close()
Exemple #9
0
async def main():

    # TODO: this really needs to be replaced
    # probably using https://docs.python.org/3.8/library/functools.html#functools.partial
    global client
    global plugin_loader

    # Read config file
    config = Config("config.yaml")

    # Configure the database
    store = Storage(config.database_filepath)

    # Configuration options for the AsyncClient
    client_config = AsyncClientConfig(
        max_limit_exceeded=0,
        max_timeouts=0,
        store_sync_tokens=True,
        encryption_enabled=config.enable_encryption,
    )

    # Initialize the matrix client
    client = AsyncClient(
        config.homeserver_url,
        config.user_id,
        device_id=config.device_id,
        store_path=config.store_filepath,
        config=client_config,
    )

    # instantiate the pluginLoader
    plugin_loader = PluginLoader()

    # Set up event callbacks
    callbacks = Callbacks(client, store, config, plugin_loader)
    client.add_event_callback(callbacks.message, (RoomMessageText, ))
    client.add_event_callback(callbacks.invite, (InviteEvent, ))
    client.add_event_callback(callbacks.event_unknown, (UnknownEvent, ))
    client.add_response_callback(run_plugins)

    # Keep trying to reconnect on failure (with some time in-between)
    error_retries: int = 0
    while True:
        try:
            # Try to login with the configured username/password
            try:
                login_response = await client.login(
                    password=config.user_password,
                    device_name=config.device_name,
                )

                # Check if login failed
                if type(login_response) == LoginError:
                    logger.error(
                        f"Failed to login: {login_response.message}, retrying in 15s... ({error_retries})"
                    )
                    # try logging in a few times to work around temporary login errors during homeserver restarts
                    if error_retries < 3:
                        error_retries += 1
                        await sleep(15)
                        continue
                    else:
                        return False
                else:
                    error_retries = 0

            except LocalProtocolError as e:
                # There's an edge case here where the user enables encryption but hasn't installed
                # the correct C dependencies. In that case, a LocalProtocolError is raised on login.
                # Warn the user if these conditions are met.
                if config.enable_encryption:
                    logger.fatal(
                        "Failed to login and encryption is enabled. Have you installed the correct dependencies? "
                        "https://github.com/poljar/matrix-nio#installation")
                    return False
                else:
                    # We don't know why this was raised. Throw it at the user
                    logger.fatal(f"Error logging in: {e}")

            # Login succeeded!

            # Sync encryption keys with the server
            # Required for participating in encrypted rooms
            if client.should_upload_keys:
                await client.keys_upload()

            logger.info(f"Logged in as {config.user_id}")
            await client.sync_forever(timeout=30000, full_state=True)

        except (ClientConnectionError, ServerDisconnectedError, AttributeError,
                asyncio.TimeoutError) as err:
            logger.debug(err)
            logger.warning(
                f"Unable to connect to homeserver, retrying in 15s...")

            # Sleep so we don't bombard the server with login requests
            await sleep(15)
        finally:
            # Make sure to close the client connection on disconnect
            await client.close()
Exemple #10
0
import generateStructurePool as structurePool
from callbacks import Callbacks

import random
import os

# Library to deal with jamo
import hgtk

# Generate the pool using the given CSV files
NOFILTERPOOL, POOL = pool.generate(
    vocabCSVs=["infile.csv", "additionalVocab/names.csv"],
    secondary_sort="Classification")
STRUCTUREPOOL = structurePool.generate()

c = Callbacks()
defaultCharts = [c.tenseChart, c.formalityChart]


# Prints the meaning, pronunciation, and any notes of the given words
def print_word_meaning(words):
    [
        print(
            f"\t{word['Hangul']}: {word['Meaning']}\t\t\t[{word['Speech Part']}{', ' if word['Notes'] != '' else ''}\x1B[3m{word['Notes']}\x1B[23m]"
        ) for word in words
    ]


# Generates a sentence
def createSentence(count=1):
 def __init__(self):
     self.model = Model()
     self.Model = self.model.create_model()
     self.callback = Callbacks()
Exemple #12
0
async def main():  # noqa
    """Create bot as Matrix client and enter event loop."""
    # Read config file
    # A different config file path can be specified
    # as the first command line argument
    if len(sys.argv) > 1:
        config_filepath = sys.argv[1]
    else:
        config_filepath = "config.yaml"
    config = Config(config_filepath)

    # Configure the database
    store = Storage(config.database_filepath)

    # Configuration options for the AsyncClient
    client_config = AsyncClientConfig(
        max_limit_exceeded=0,
        max_timeouts=0,
        store_sync_tokens=True,
        encryption_enabled=True,
    )

    # Initialize the matrix client
    client = AsyncClient(
        config.homeserver_url,
        config.user_id,
        device_id=config.device_id,
        store_path=config.store_filepath,
        config=client_config,
    )

    # Set up event callbacks
    callbacks = Callbacks(client, store, config)
    client.add_event_callback(callbacks.message, (RoomMessageText, ))
    client.add_event_callback(callbacks.invite, (InviteMemberEvent, ))
    client.add_to_device_callback(callbacks.accept_all_verify,
                                  (KeyVerificationEvent, ))

    # Keep trying to reconnect on failure (with some time in-between)
    while True:
        try:
            # Try to login with the configured username/password
            try:
                if config.access_token:
                    logger.debug("Using access token from config file to log "
                                 f"in. access_token={config.access_token}")

                    client.restore_login(user_id=config.user_id,
                                         device_id=config.device_id,
                                         access_token=config.access_token)
                else:
                    logger.debug("Using password from config file to log in.")
                    login_response = await client.login(
                        password=config.user_password,
                        device_name=config.device_name,
                    )

                    # Check if login failed
                    if type(login_response) == LoginError:
                        logger.error("Failed to login: "******"{login_response.message}")
                        return False
                    logger.info((f"access_token of device {config.device_name}"
                                 f" is: \"{login_response.access_token}\""))
            except LocalProtocolError as e:
                # There's an edge case here where the user hasn't installed
                # the correct C dependencies. In that case, a
                # LocalProtocolError is raised on login.
                logger.fatal(
                    "Failed to login. "
                    "Have you installed the correct dependencies? "
                    "Error: %s", e)
                return False

            # Login succeeded!
            logger.debug(f"Logged in successfully as user {config.user_id} "
                         f"with device {config.device_id}.")
            # Sync encryption keys with the server
            # Required for participating in encrypted rooms
            if client.should_upload_keys:
                await client.keys_upload()

            if config.change_device_name:
                content = {"display_name": config.device_name}
                resp = await client.update_device(config.device_id, content)
                if isinstance(resp, UpdateDeviceError):
                    logger.debug(f"update_device failed with {resp}")
                else:
                    logger.debug(f"update_device successful with {resp}")

            await client.sync(timeout=30000, full_state=True)
            for device_id, olm_device in client.device_store[
                    config.user_id].items():
                logger.info("Setting up trust for my own "
                            f"device {device_id} and session key "
                            f"{olm_device.keys}.")
                client.verify_device(olm_device)

            await client.sync_forever(timeout=30000, full_state=True)

        except (ClientConnectionError, ServerDisconnectedError):
            logger.warning(
                "Unable to connect to homeserver, retrying in 15s...")

            # Sleep so we don't bombard the server with login requests
            sleep(15)
        finally:
            # Make sure to close the client connection on disconnect
            await client.close()
Exemple #13
0
async def main():
    """Entry point."""
    # Read config file
    config = Config("config.yaml")

    # Configure the database
    store = Storage(config.database_filepath)

    # Configuration options for the AsyncClient
    client_config = AsyncClientConfig(
        max_limit_exceeded=0,
        max_timeouts=0,
        # store_sync_tokens=True,
        encryption_enabled=config.enable_encryption,
    )

    # Initialize the matrix client
    client = AsyncClient(
        config.homeserver_url,
        config.user_id,
        device_id=config.device_id,
        store_path=config.store_filepath,
        config=client_config,
    )

    # Assign an access token to the bot instead of logging in and creating a new device
    client.access_token = config.access_token

    # Set up event callbacks
    callbacks = Callbacks(client, store, config)
    client.add_event_callback(callbacks.message, (RoomMessageText,))
    client.add_event_callback(callbacks.invite, (InviteMemberEvent,))
    client.add_event_callback(callbacks.joined, (RoomMemberEvent,))

    # Create a new sync token, attempting to load one from the database if it has one already
    sync_token = SyncToken(store)

    # Keep trying to reconnect on failure (with some time in-between)
    while True:
        # try:
        # Try to login with the configured username/password
        # try:
        #     login_response = await client.login(
        #         password=config.user_password,
        #         device_name=config.device_name,
        #     )

        #     # Check if login failed
        #     if type(login_response) == LoginError:
        #         logger.error(f"Failed to login: %s", login_response.message)
        #         return False
        # except LocalProtocolError as e:
        #     # There's an edge case here where the user enables encryption
        #     # but hasn't installed the correct C dependencies. In that case,
        #     # a LocalProtocolError is raised on login.
        #     # Warn the user if these conditions are met.
        #     if config.enable_encryption:
        #         logger.fatal(
        #             "Failed to login and encryption is enabled. "
        #             "Have you installed the correct dependencies? "
        #             "https://github.com/poljar/matrix-nio#installation"
        #         )
        #         return False
        #     else:
        #         # We don't know why this was raised. Throw it at the user
        #         logger.fatal("Error logging in: %s", e)
        #         return False

        # Login succeeded!

        # ===============================
        # Sync encryption keys with the server
        # Required for participating in encrypted rooms
        # if client.should_upload_keys:
        #     await client.keys_upload()

        # logger.info(f"Logged in as {config.user_id}")
        # await client.sync_forever(timeout=30000, full_state=True)
        # ===============================

        # ===============================
        logger.debug("Syncing: %s", sync_token.token)
        sync_response = await client.sync(timeout=30000, since=sync_token.token)

        # Check if the sync had an errors
        if type(sync_response) == SyncError:
            logger.warning("Error in client sync: %s", sync_response.message)
            continue

        # Save the latest sync token to the database
        token = sync_response.next_batch
        if token:
            sync_token.update(token)
Exemple #14
0
class Mainwindow:
    """A class to represent main window of a program"""

    def __init__(self):
        """Init the window"""
        self.root = Tk()

        self.settings = Settings()
        self.root.title(self.settings.title)
        self.root.geometry(self.settings.geometry)
        self._set_background()
        self.root.iconbitmap(self.settings.icon)

        self.callbacks = Callbacks()

        # init entry text
        self.password = Entry(
            self.root, show="*", width=self.settings.entry_width, border=self.settings.entry_border)
        self.password.grid(row=1, column=1)
        # self.password.pack()

        # init buttons
        self.encryptionButton = Button(self.root, text="Encrypt",
                                       padx=self.settings.padx, pady=self.settings.pady, command=lambda: self.callbacks.encrypt_button(self.password.get()))
        self.encryptionButton.grid(row=2, column=0)

        self.decryptionButton = Button(self.root, text="Decrypt",
                                       padx=self.settings.padx, pady=self.settings.pady, command=lambda: self.callbacks.decrypt_button(self.password.get()))
        self.decryptionButton.grid(row=2, column=2)

        self.decryptionButton = Button(self.root, text="Open file",
                                       padx=self.settings.padx, pady=self.settings.pady, command=self.callbacks.open_file)
        self.decryptionButton.grid(row=2, column=1)



    def _set_background(self):
        """set background image"""
        self.bg_image = Image.open(self.settings.bg_image)
        self.bg_image_tk = ImageTk.PhotoImage(self.bg_image)
        self.bg_label = Label(self.root, image=self.bg_image_tk)
        self.bg_label.grid(row=0, column=0, columnspan=3, rowspan=4)

    def loop(self):
        self.root.mainloop()
Exemple #15
0
class Mainwindow:
    """A class to represent main window of a program"""
    def __init__(self):
        """Init the window"""
        self.root = Tk()
        self.settings = Settings()
        self.root.title(self.settings.title)
        self.root.geometry(self.settings.geometry)
        self._set_background()
        self.root.iconbitmap(self.settings.icon)
        self.path = ""
        self.password = ""

        self.callbacks = Callbacks()

        # init entry text
        self.pass_label = Label(self.root, text="Password: "******"*",
                              width=self.settings.entry_width,
                              border=self.settings.entry_border)
        self.password.grid(row=1, column=2, columnspan=2)

        # init entry local path
        self.path_text = Label(self.root, text="Local path: ")
        self.path_text.grid(row=2, column=0)
        self.path_label = Label(
            self.root,
            text="Please click load file button to select a file",
            width=self.settings.entry_width + 4,
            border=self.settings.entry_border)
        self.path_label.grid(row=2, column=2, columnspan=2)

        self.__buttons_init()

    def __buttons_init(self):
        """funcion to manage buttons"""
        self.encryptionButton = Button(
            self.root,
            text="Encrypt",
            padx=self.settings.padx,
            pady=self.settings.pady,
            command=lambda: self.callbacks.encrypt_button(
                self.password.get(), self.path))
        self.encryptionButton.grid(row=3, column=4)

        self.decryptionButton = Button(
            self.root,
            text="Decrypt",
            padx=self.settings.padx,
            pady=self.settings.pady,
            command=lambda: self.callbacks.decrypt_button(
                self.password.get(), self.path))
        self.decryptionButton.grid(row=4, column=4)

        self.openButton = Button(self.root,
                                 text="Load file",
                                 padx=self.settings.padx,
                                 pady=self.settings.pady,
                                 command=self.open_file)
        self.openButton.grid(row=2, column=4)

    def _set_background(self):
        """set background image"""
        self.bg_image = Image.open(self.settings.bg_image)
        self.bg_image_tk = ImageTk.PhotoImage(self.bg_image)
        self.bg_label = Label(self.root, image=self.bg_image_tk)
        self.bg_label.grid(row=0,
                           column=0,
                           columnspan=self.settings.columnspan,
                           rowspan=self.settings.rowspan)

    def open_file(self):
        # init open file dialog
        self.path = filedialog.askopenfilename(initialdir="/",
                                               title="Select a file")
        self.path_label = Label(self.root,
                                text=self.path,
                                width=self.settings.entry_width,
                                border=self.settings.entry_border)
        self.path_label.grid(row=2, column=3)

    def loop(self):
        self.root.mainloop()
Exemple #16
0
	def test_withoutFlags(self):
		val = 0
		nb = 0

		def fn1(v):
			nonlocal val, nb
			val = v
			nb += 1

		def fn2(v):
			nonlocal val, nb
			val = -v
			nb += 1

		def check1(v):
			nonlocal self, val, nb
			self.assertIs(v,val)
			nb += 1

		def check2(v):
			nonlocal self, val, nb
			self.assertIs(-v,val)
			nb += 1

		c = Callbacks()
		c.add(fn1).add(check1)
		c.fire(1)
		c.add(fn2).add(check2)
		c.fire(2)
		c.remove(fn2).remove(check2).add(check1)
		c.fire(3)

		self.assertEqual(nb,9)