Ejemplo n.º 1
0
async def draw(messages_queue, sending_queue, status_updates_queue):
    root = tk.Tk()

    root.title('Chat')

    root_frame = tk.Frame()
    root_frame.pack(fill="both", expand=True)

    status_labels = create_status_panel(root_frame)

    input_frame = tk.Frame(root_frame)
    input_frame.pack(side="bottom", fill=tk.X)

    input_field = tk.Entry(input_frame)
    input_field.pack(side="left", fill=tk.X, expand=True)

    input_field.bind(
        "<Return>",
        lambda event: process_new_message(input_field, sending_queue))

    send_button = tk.Button(input_frame)
    send_button["text"] = "Отправить"
    send_button["command"] = lambda: process_new_message(
        input_field, sending_queue)
    send_button.pack(side="left")

    conversation_panel = ScrolledText(root_frame, wrap='none')
    conversation_panel.pack(side="top", fill="both", expand=True)

    async with create_handy_nursery() as nursery:
        nursery.start_soon(update_tk(root_frame))
        nursery.start_soon(
            update_conversation_history(conversation_panel, messages_queue))
        nursery.start_soon(
            update_status_panel(status_labels, status_updates_queue))
Ejemplo n.º 2
0
async def main():
    command_line_arguments = get_command_line_arguments()

    chat_host = command_line_arguments.host
    chat_port = command_line_arguments.port
    user_credentials_output_filepath = command_line_arguments.output

    nickname_queue = asyncio.Queue()
    register_button_state_queue = asyncio.Queue()

    async with create_handy_nursery() as nursery:
        nursery.start_soon(
            gui.draw(
                nickname_queue=nickname_queue,
                register_button_state_queue=register_button_state_queue,
            ),
        )
        nursery.start_soon(
            run_chat_registrator(
                host=chat_host,
                port=chat_port,
                nickname_queue=nickname_queue,
                register_button_state_queue=register_button_state_queue,
                user_credentials_output_filepath=user_credentials_output_filepath,
            )
        )
Ejemplo n.º 3
0
async def handle_connection(host, reader_port, writer_port, history, token,
                            queues):
    while True:
        try:
            async with mc.get_connection(host, writer_port, history,
                                         queues) as streams:
                async with timeout(CONNECTION_TIMEOUT):
                    is_authorized, account_info = await mc.authorise(
                        *streams, token)
                    if not is_authorized:
                        messagebox.showerror(
                            'Неизвестный токен',
                            'Проверьте токен или зарегистрируйте заново.')
                        raise InvalidToken
                    event = gui.NicknameReceived(account_info['nickname'])
                    queues['status_updates_queue'].put_nowait(event)

                async with utils.create_handy_nursery() as nursery:
                    nursery.start_soon(
                        mc.restore_history(history, queues['messages_queue']))
                    nursery.start_soon(
                        read_msgs(host, reader_port, history, queues))
                    nursery.start_soon(send_msgs(*streams, queues))
                    nursery.start_soon(
                        watch_for_connection(queues["watchdog_queue"]))
                    nursery.start_soon(
                        ping_pong(*streams, queues["watchdog_queue"]))

        except (ConnectionRefusedError, ConnectionResetError, ConnectionError,
                asyncio.TimeoutError):
            continue
        else:
            break
Ejemplo n.º 4
0
async def run_app(host: str, reader_port: int, writer_port: int, token: str,
                  history_path: str) -> None:

    messages_queue = asyncio.Queue()
    sending_queue = asyncio.Queue()
    status_updates_queue = asyncio.Queue()
    history_queue = asyncio.Queue()
    watchdog_queue = asyncio.Queue()

    history.load_history(history_path, messages_queue)

    async with create_handy_nursery() as nursery:
        nursery.start_soon(
            gui.draw(messages_queue, sending_queue, status_updates_queue))
        nursery.start_soon(
            history.save_messages(filepath=history_path,
                                  history_queue=history_queue))
        nursery.start_soon(
            handle_connection(host=host,
                              reader_port=reader_port,
                              writer_port=writer_port,
                              token=token,
                              messages_queue=messages_queue,
                              status_queue=status_updates_queue,
                              history_queue=history_queue,
                              sending_queue=sending_queue,
                              watchdog_queue=watchdog_queue))
Ejemplo n.º 5
0
async def handle_articles(request, morph, charged_words, max_urls_count=10):
    urls_string = request.query.get('urls')

    if not urls_string:
        return web.json_response(
            {'error': 'articles URLs not given'},
            status=400,
        )

    urls = urls_string.split(',')

    if len(urls) > max_urls_count:
        return web.json_response(
            {'error': f'too many URLs in request, should be {max_urls_count} or less'},
            status=400,
        )

    async with ClientSession() as session:
        async with create_handy_nursery() as nursery:
            tasks = [
                nursery.start_soon(
                    process_article(session, article_url, morph, charged_words),
                )
                for article_url in urls
            ]
            done_tasks, _ = await asyncio.wait(tasks)

    return web.json_response([task.result() for task in done_tasks])
Ejemplo n.º 6
0
async def send_msgs(host: str, port: int, token: Token,
                    sending_queue: asyncio.Queue, status_queue: asyncio.Queue,
                    watchdog_queue: asyncio.Queue) -> None:
    authorized = False
    async with connect(
            host=host,
            port=port,
            status_queue=status_queue,
            connect_state_mode=gui.SendingConnectionStateChanged) as (reader,
                                                                      writer):

        if not token.is_exist:
            status_queue.put_nowait(gui.SendingConnectionStateChanged.CLOSED)
            token.value, user = await registration(reader, writer)
            status_queue.put_nowait(
                gui.SendingConnectionStateChanged.INITIATED)
            authorized = True
        await watchdog_queue.put(WatchdogSwitcher.ENABLE)

        if not authorized:
            await watchdog_queue.put("Prompt before auth")
            user = await authorise(reader, writer, token.value)

        await status_queue.put(gui.NicknameReceived(user))
        await watchdog_queue.put("Authorization done")
        status_queue.put_nowait(gui.SendingConnectionStateChanged.ESTABLISHED)

        async with create_handy_nursery() as nursery:
            nursery.start_soon(
                send_message(writer=writer,
                             sending_queue=sending_queue,
                             watchdog_queue=watchdog_queue))
            nursery.start_soon(ping_pong(reader, writer, watchdog_queue))
Ejemplo n.º 7
0
async def handle_connection(host: str, reader_port: int, writer_port: int,
                            token: str, messages_queue: asyncio.Queue,
                            status_queue: asyncio.Queue,
                            history_queue: asyncio.Queue,
                            sending_queue: asyncio.Queue,
                            watchdog_queue: asyncio.Queue) -> None:
    token = Token(token)
    while True:
        try:
            async with create_handy_nursery() as nursery:
                nursery.start_soon(
                    connection.read_msgs(host=host,
                                         port=reader_port,
                                         messages_queue=messages_queue,
                                         status_queue=status_queue,
                                         history_queue=history_queue,
                                         watchdog_queue=watchdog_queue))
                nursery.start_soon(
                    connection.send_msgs(host=host,
                                         port=writer_port,
                                         token=token,
                                         sending_queue=sending_queue,
                                         status_queue=status_queue,
                                         watchdog_queue=watchdog_queue))
                nursery.start_soon(
                    connection.watch_for_connection(
                        watchdog_queue=watchdog_queue))
        except aionursery.MultiError as e:
            if not any(isinstance(ex, ConnectionError) for ex in e.exceptions):
                raise
        except ConnectionError:
            await asyncio.sleep(RECONNECT_DELAY)
        else:
            return
Ejemplo n.º 8
0
async def registration(reader: asyncio.StreamReader,
                       writer: asyncio.StreamWriter) -> str:
    login_queue = asyncio.Queue(maxsize=1)
    async with create_handy_nursery() as nursery:
        nursery.start_soon(register_draw(login_queue))
        tok = nursery.start_soon(register(reader, writer, login_queue))
    return tok.result()
Ejemplo n.º 9
0
async def main():
    dotenv.load_dotenv()
    registration_queue = asyncio.Queue()
    args = get_args()

    async with utils.create_handy_nursery() as nursery:
        nursery.start_soon(draw(registration_queue))

        nursery.start_soon(
            handle_connection(args.host, args.writer_port, registration_queue))
Ejemplo n.º 10
0
async def main():
    command_line_arguments = get_command_line_arguments()

    chat_host = command_line_arguments.host
    chat_read_port = command_line_arguments.read_port
    chat_write_port = command_line_arguments.write_port
    user_credentials_filepath = command_line_arguments.credentials
    chat_auth_token = command_line_arguments.token
    output_filepath = command_line_arguments.output

    if not chat_auth_token:
        user_credentials = await load_json_data(user_credentials_filepath)

        if not user_credentials:
            sys.exit('Auth token not given')

        chat_auth_token = user_credentials['account_hash']

    displayed_messages_queue = asyncio.Queue()
    written_to_file_messages_queue = asyncio.Queue()
    sending_messages_queue = asyncio.Queue()
    status_updates_queue = asyncio.Queue()

    watchdog_logger.setLevel(level=logging.INFO)
    console_handler = logging.StreamHandler()
    console_handler.setLevel(level=logging.INFO)
    console_handler.setFormatter(
        logging.Formatter('%(name)s:%(levelname)s:%(message)s'))
    watchdog_logger.addHandler(console_handler)

    async with create_handy_nursery() as nursery:
        nursery.start_soon(
            handle_connection(
                host=chat_host,
                read_port=chat_read_port,
                write_port=chat_write_port,
                auth_token=chat_auth_token,
                displayed_messages_queue=displayed_messages_queue,
                written_to_file_messages_queue=written_to_file_messages_queue,
                sending_messages_queue=sending_messages_queue,
                status_updates_queue=status_updates_queue,
            ), )
        nursery.start_soon(
            gui.draw(
                messages_queue=displayed_messages_queue,
                sending_queue=sending_messages_queue,
                status_updates_queue=status_updates_queue,
            ), )
        nursery.start_soon(
            save_messages(
                output_filepath=output_filepath,
                messages_queue=written_to_file_messages_queue,
            ), )
Ejemplo n.º 11
0
async def main():
    dotenv.load_dotenv()
    queues = get_queues()
    args = get_args()

    async with utils.create_handy_nursery() as nursery:
        nursery.start_soon(
            gui.draw(queues['messages_queue'], queues['sending_queue'],
                     queues['status_updates_queue']))
        nursery.start_soon(
            handle_connection(args.host, args.reader_port, args.writer_port,
                              args.history, args.token, queues))
        nursery.start_soon(save_messages(args.history,
                                         queues['history_queue']))
Ejemplo n.º 12
0
async def draw(messages_queue, sending_queue, status_updates_queue):
    root = tk.Tk()

    root.title('Minecraft Chat')

    root_frame = tk.Frame()
    root_frame.pack(fill='both', expand=True)

    status_labels = create_status_panel(root_frame)

    input_frame = tk.Frame(root_frame)
    input_frame.pack(side='bottom', fill=tk.X)

    input_field = tk.Entry(input_frame)
    input_field.pack(side='left', fill=tk.X, expand=True)

    input_field.bind(
        '<Return>',
        lambda event: move_message_to_queue(input_field, sending_queue),
    )

    send_button = tk.Button(input_frame)
    send_button['text'] = 'Send'
    send_button['command'] = lambda: move_message_to_queue(
        input_field, sending_queue)
    send_button.pack(side='left')

    conversation_panel = ScrolledText(root_frame, wrap='none')
    conversation_panel.pack(side='top', fill='both', expand=True)
    conversation_panel.vbar.bind('<Enter>', disable_autoscrolling)
    conversation_panel.vbar.bind('<Leave>', enable_autoscrolling)

    root.update_idletasks()

    set_window_to_screen_center(root)

    async with create_handy_nursery() as nursery:
        nursery.start_soon(update_tk(root_frame=root_frame, ), )
        nursery.start_soon(
            update_conversation_history(
                panel=conversation_panel,
                messages_queue=messages_queue,
            ), )
        nursery.start_soon(
            update_status_panel(
                status_labels=status_labels,
                status_updates_queue=status_updates_queue,
            ), )
Ejemplo n.º 13
0
async def run_chat_writer(host, port, auth_token, sending_messages_queue,
                          status_updates_queue, watchdog_messages_queue,
                          successful_connection_info_queue):
    status_updates_queue.put_nowait(
        gui.SendingConnectionStateChanged.INITIATED)

    reader, writer = await asyncio.open_connection(host=host, port=port)

    try:
        status_updates_queue.put_nowait(
            gui.SendingConnectionStateChanged.ESTABLISHED)
        successful_connection_info_queue.put_nowait(True)

        user_credentials = await authorise(
            reader=reader,
            writer=writer,
            auth_token=auth_token,
            watchdog_messages_queue=watchdog_messages_queue,
        )
        if user_credentials is None:
            raise InvalidToken()

        status_updates_queue.put_nowait(
            gui.NicknameReceived(user_credentials["nickname"]), )

        async with create_handy_nursery() as nursery:
            nursery.start_soon(
                send_messages(
                    reader=reader,
                    writer=writer,
                    sending_messages_queue=sending_messages_queue,
                    watchdog_messages_queue=watchdog_messages_queue,
                ), )
            nursery.start_soon(
                send_empty_messages(
                    reader=reader,
                    writer=writer,
                    watchdog_messages_queue=watchdog_messages_queue,
                ), )
    finally:
        writer.close()
        status_updates_queue.put_nowait(
            gui.SendingConnectionStateChanged.CLOSED)
async def draw(nickname_queue, register_button_state_queue):
    root = tk.Tk()

    root.title('Minecraft Chat Registrator')
    root.resizable(False, False)

    root_frame = tk.Frame()
    root_frame.pack(fill='both', expand=True)

    info_label = tk.Label(root_frame,
                          height=2,
                          width=30,
                          fg='black',
                          font='arial 14',
                          anchor='w')
    info_label.pack(side='top', fill=tk.X, padx=10)
    info_label['text'] = 'Enter preferred nickname:'

    nickname_input_field = tk.Entry(root_frame, font='arial 18')
    nickname_input_field.pack(side='top', fill=tk.X, expand=True, padx=10)

    register_button = tk.Button(root_frame, font='arial 14', height=1)
    register_button['text'] = 'Register'
    register_button['command'] = lambda: handle_register_button_click(
        button=register_button,
        nickname_input_field=nickname_input_field,
        nickname_queue=nickname_queue,
    )
    register_button.pack(side='top', ipady=10, pady=10)

    root.update_idletasks()

    set_window_to_screen_center(root)

    async with create_handy_nursery() as nursery:
        nursery.start_soon(update_tk(root_frame=root_frame, ), )
        nursery.start_soon(
            handle_button_state(
                button=register_button,
                button_state_queue=register_button_state_queue,
            ))
Ejemplo n.º 15
0
async def draw(registration_queue):
    root = tk.Tk()
    root.title('Регистрация нового пользователя')

    root_frame = tk.Frame(root, width=300)
    root_frame.pack()

    label = tk.Label(height=1, text='Введите ник')
    label.pack()

    username_input = tk.Entry(width=20)
    username_input.pack(pady=5)

    register_button = tk.Button(text='Зарегистрироваться', bd=1)
    register_button.bind(
        '<Button-1>',
        lambda event: get_username(username_input, registration_queue))
    register_button.pack(pady=10)

    async with utils.create_handy_nursery() as nursery:
        nursery.start_soon(gui.update_tk(root_frame))
Ejemplo n.º 16
0
async def handler(charged_words: List[str],
                  morph: pymorphy2.MorphAnalyzer,
                  request: web.Request) -> web.Response:

    urls = request.query.get('urls')
    if not urls:
        return web.json_response({'error': 'no urls given'}, status=400)
    urls_list = urls.rstrip(',').split(',')

    if len(urls_list) > 10:
        response = {'error': 'too many urls in request, should be 10 or less'}
        return web.json_response(response, status=400)

    async with aiohttp.ClientSession() as session:
        async with create_handy_nursery() as nursery:
            tasks = []
            for url in urls_list:
                task = nursery.start_soon(process_article(session, morph,
                                                          charged_words, url))
                tasks.append(task)

    list_of_results = [task.result() for task in tasks]
    return web.json_response(list_of_results)
Ejemplo n.º 17
0
async def handle_connection(host,
                            read_port,
                            write_port,
                            auth_token,
                            displayed_messages_queue,
                            written_to_file_messages_queue,
                            sending_messages_queue,
                            status_updates_queue,
                            connection_attempts_count_without_timeout=2,
                            timeout_between_connection_attempts=2):
    watchdog_messages_queue = asyncio.Queue()
    chat_reader_successful_connection_info_queue = asyncio.Queue()
    chat_writer_successful_connection_info_queue = asyncio.Queue()

    current_connection_attempt = 0

    while True:
        try:
            current_connection_attempt += 1

            async with create_handy_nursery() as nursery:
                nursery.start_soon(
                    run_chat_reader(
                        host=host,
                        port=read_port,
                        displayed_messages_queue=displayed_messages_queue,
                        written_to_file_messages_queue=
                        written_to_file_messages_queue,
                        status_updates_queue=status_updates_queue,
                        watchdog_messages_queue=watchdog_messages_queue,
                        successful_connection_info_queue=
                        chat_reader_successful_connection_info_queue,
                    ), )
                nursery.start_soon(
                    run_chat_writer(
                        host=host,
                        port=write_port,
                        auth_token=auth_token,
                        sending_messages_queue=sending_messages_queue,
                        status_updates_queue=status_updates_queue,
                        watchdog_messages_queue=watchdog_messages_queue,
                        successful_connection_info_queue=
                        chat_writer_successful_connection_info_queue,
                    ), )
                nursery.start_soon(
                    watch_for_connection(
                        watchdog_messages_queue=watchdog_messages_queue, ), )
            return
        except MultiError as e:
            for exc in e.exceptions:
                if not isinstance(exc, socket.gaierror):
                    raise
        except (ConnectionError, socket.gaierror):
            pass

        if (not chat_reader_successful_connection_info_queue.empty()
                and not chat_writer_successful_connection_info_queue.empty()):
            current_connection_attempt = 0

        if not chat_reader_successful_connection_info_queue.empty():
            chat_reader_successful_connection_info_queue.get_nowait()

        if not chat_writer_successful_connection_info_queue.empty():
            chat_writer_successful_connection_info_queue.get_nowait()

        if current_connection_attempt >= connection_attempts_count_without_timeout:
            await asyncio.sleep(timeout_between_connection_attempts)
Ejemplo n.º 18
0
async def ping_pong(reader: asyncio.StreamReader, writer: asyncio.StreamWriter,
                    watchdog_queue: asyncio.Queue) -> None:
    async with create_handy_nursery() as nursery:
        nursery.start_soon(_ping(writer))
        nursery.start_soon(_pong(reader, watchdog_queue))