From 2f4137933fdb4705231ad8137c3694af0005e457 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?poljar=20=28Damir=20Jeli=C4=87=29?= Date: Wed, 21 Feb 2018 17:00:11 +0100 Subject: [PATCH] Reformat the source tree using yapf. --- main.py | 158 ++++++++++++--------------------------- matrix/api.py | 189 ++++++++++++++++------------------------------- matrix/colors.py | 107 ++++++++++++--------------- matrix/http.py | 26 ++++--- matrix/server.py | 143 ++++++++++++----------------------- 5 files changed, 219 insertions(+), 404 deletions(-) diff --git a/main.py b/main.py index fec2737..694896d 100644 --- a/main.py +++ b/main.py @@ -31,26 +31,16 @@ from typing import (List, Set, Dict, Tuple, Text, Optional, AnyStr, Deque, Any) from matrix.colors import Formatted from matrix.utf import utf8_decode from matrix.http import HttpResponse -from matrix.api import ( - MessageType, - MatrixSendMessage -) +from matrix.api import (MessageType, MatrixSendMessage) from matrix.messages import handle_http_response # Weechat searches for the registered callbacks in the scope of the main script # file, import the callbacks here so weechat can find them. -from matrix.commands import ( - hook_commands, - hook_page_up, - matrix_command_cb, - matrix_command_join_cb, - matrix_command_part_cb, - matrix_command_invite_cb, - matrix_command_topic_cb, - matrix_command_pgup_cb, - matrix_redact_command_cb, - matrix_command_buf_clear_cb -) +from matrix.commands import (hook_commands, hook_page_up, matrix_command_cb, + matrix_command_join_cb, matrix_command_part_cb, + matrix_command_invite_cb, matrix_command_topic_cb, + matrix_command_pgup_cb, matrix_redact_command_cb, + matrix_command_buf_clear_cb) from matrix.server import ( MatrixServer, @@ -62,29 +52,16 @@ from matrix.server import ( matrix_config_server_change_cb, ) -from matrix.bar_items import ( - init_bar_items, - matrix_bar_item_name, - matrix_bar_item_plugin, - matrix_bar_item_lag -) +from matrix.bar_items import (init_bar_items, matrix_bar_item_name, + matrix_bar_item_plugin, matrix_bar_item_lag) from matrix.completion import ( - init_completion, - matrix_command_completion_cb, - matrix_server_command_completion_cb, - matrix_debug_completion_cb, - matrix_message_completion_cb, - matrix_server_completion_cb -) + init_completion, matrix_command_completion_cb, + matrix_server_command_completion_cb, matrix_debug_completion_cb, + matrix_message_completion_cb, matrix_server_completion_cb) -from matrix.utils import ( - key_from_value, - server_buffer_prnt, - prnt_debug, - tags_from_line_data, - server_buffer_set_title -) +from matrix.utils import (key_from_value, server_buffer_prnt, prnt_debug, + tags_from_line_data, server_buffer_set_title) from matrix.plugin_options import ( DebugType, @@ -92,35 +69,29 @@ from matrix.plugin_options import ( ServerBufferType, ) -from matrix.config import ( - matrix_config_init, - matrix_config_read, - matrix_config_free, - matrix_config_change_cb, - matrix_config_reload_cb -) +from matrix.config import (matrix_config_init, matrix_config_read, + matrix_config_free, matrix_config_change_cb, + matrix_config_reload_cb) import matrix.globals from matrix.globals import W, OPTIONS, SERVERS - +# yapf: disable WEECHAT_SCRIPT_NAME = "matrix" # type: str WEECHAT_SCRIPT_DESCRIPTION = "matrix chat plugin" # type: str WEECHAT_SCRIPT_AUTHOR = "Damir Jelić " # type: str WEECHAT_SCRIPT_VERSION = "0.1" # type: str WEECHAT_SCRIPT_LICENSE = "ISC" # type: str +# yapf: enable def wrap_socket(server, file_descriptor): # type: (MatrixServer, int) -> None sock = None # type: socket.socket - temp_socket = socket.fromfd( - file_descriptor, - socket.AF_INET, - socket.SOCK_STREAM - ) + temp_socket = socket.fromfd(file_descriptor, socket.AF_INET, + socket.SOCK_STREAM) # For python 2.7 wrap_socket() doesn't work with sockets created from an # file descriptor because fromfd() doesn't return a wrapped socket, the bug @@ -142,8 +113,7 @@ def wrap_socket(server, file_descriptor): W.prnt(server.server_buffer, message) ssl_socket = server.ssl_context.wrap_socket( - sock, - do_handshake_on_connect=False, + sock, do_handshake_on_connect=False, server_hostname=server.address) # type: ssl.SSLSocket server.socket = ssl_socket @@ -189,23 +159,15 @@ def try_ssl_handshake(server): return True except ssl.SSLWantReadError: - hook = W.hook_fd( - server.socket.fileno(), - 1, 0, 0, - "ssl_fd_cb", - server.name - ) + hook = W.hook_fd(server.socket.fileno(), 1, 0, 0, "ssl_fd_cb", + server.name) server.ssl_hook = hook return False except ssl.SSLWantWriteError: - hook = W.hook_fd( - server.socket.fileno(), - 0, 1, 0, - "ssl_fd_cb", - server.name - ) + hook = W.hook_fd(server.socket.fileno(), 0, 1, 0, "ssl_fd_cb", + server.name) server.ssl_hook = hook return False @@ -215,15 +177,13 @@ def try_ssl_handshake(server): message = ("{prefix}Error while doing SSL handshake" ": {error}").format( - prefix=W.prefix("network"), - error=str_error) + prefix=W.prefix("network"), error=str_error) server_buffer_prnt(server, message) server_buffer_prnt( - server, - ("{prefix}matrix: disconnecting from server...").format( - prefix=W.prefix("network"))) + server, ("{prefix}matrix: disconnecting from server..." + ).format(prefix=W.prefix("network"))) server.disconnect() return False @@ -245,15 +205,13 @@ def receive_cb(server_name, file_descriptor): message = ("{prefix}Error while reading from " "socket: {error}").format( - prefix=W.prefix("network"), - error=str_error) + prefix=W.prefix("network"), error=str_error) server_buffer_prnt(server, message) server_buffer_prnt( - server, - ("{prefix}matrix: disconnecting from server...").format( - prefix=W.prefix("network"))) + server, ("{prefix}matrix: disconnecting from server..." + ).format(prefix=W.prefix("network"))) server.disconnect() @@ -265,9 +223,8 @@ def receive_cb(server_name, file_descriptor): "{prefix}matrix: Error while reading from socket".format( prefix=W.prefix("network"))) server_buffer_prnt( - server, - ("{prefix}matrix: disconnecting from server...").format( - prefix=W.prefix("network"))) + server, ("{prefix}matrix: disconnecting from server..." + ).format(prefix=W.prefix("network"))) server.disconnect() break @@ -296,9 +253,7 @@ def receive_cb(server_name, file_descriptor): prnt_debug(DebugType.MESSAGING, server, ("{prefix}Received message of type {t} and " "status {s}").format( - prefix=W.prefix("error"), - t=message.type, - s=status)) + prefix=W.prefix("error"), t=message.type, s=status)) # Message done, reset the parser state. server.reset_parser() @@ -310,12 +265,7 @@ def receive_cb(server_name, file_descriptor): def finalize_connection(server): - hook = W.hook_fd( - server.socket.fileno(), - 1, 0, 0, - "receive_cb", - server.name - ) + hook = W.hook_fd(server.socket.fileno(), 1, 0, 0, "receive_cb", server.name) server.fd_hook = hook server.connected = True @@ -342,8 +292,7 @@ def connect_cb(data, status, gnutls_rc, sock, error, ip_address): elif status_value == W.WEECHAT_HOOK_CONNECT_ADDRESS_NOT_FOUND: W.prnt( server.server_buffer, - '{address} not found'.format(address=ip_address) - ) + '{address} not found'.format(address=ip_address)) elif status_value == W.WEECHAT_HOOK_CONNECT_IP_ADDRESS_NOT_FOUND: W.prnt(server.server_buffer, 'IP address not found') @@ -352,10 +301,8 @@ def connect_cb(data, status, gnutls_rc, sock, error, ip_address): W.prnt(server.server_buffer, 'Connection refused') elif status_value == W.WEECHAT_HOOK_CONNECT_PROXY_ERROR: - W.prnt( - server.server_buffer, - 'Proxy fails to establish connection to server' - ) + W.prnt(server.server_buffer, + 'Proxy fails to establish connection to server') elif status_value == W.WEECHAT_HOOK_CONNECT_LOCAL_HOSTNAME_ERROR: W.prnt(server.server_buffer, 'Unable to set local hostname') @@ -377,8 +324,7 @@ def connect_cb(data, status, gnutls_rc, sock, error, ip_address): else: W.prnt( server.server_buffer, - 'Unexpected error: {status}'.format(status=status_value) - ) + 'Unexpected error: {status}'.format(status=status_value)) server.disconnect(reconnect=True) return W.WEECHAT_RC_OK @@ -403,10 +349,7 @@ def room_input_cb(server_name, buffer, input_data): formatted_data = Formatted.from_input_line(input_data) message = MatrixSendMessage( - server.client, - room_id=room_id, - formatted_message=formatted_data - ) + server.client, room_id=room_id, formatted_message=formatted_data) server.send_or_queue(message) return W.WEECHAT_RC_OK @@ -414,8 +357,8 @@ def room_input_cb(server_name, buffer, input_data): @utf8_decode def room_close_cb(data, buffer): - W.prnt("", "Buffer '%s' will be closed!" % - W.buffer_get_string(buffer, "name")) + W.prnt("", + "Buffer '%s' will be closed!" % W.buffer_get_string(buffer, "name")) return W.WEECHAT_RC_OK @@ -432,21 +375,14 @@ def autoconnect(servers): if __name__ == "__main__": - if W.register(WEECHAT_SCRIPT_NAME, - WEECHAT_SCRIPT_AUTHOR, - WEECHAT_SCRIPT_VERSION, - WEECHAT_SCRIPT_LICENSE, - WEECHAT_SCRIPT_DESCRIPTION, - 'matrix_unload_cb', - ''): + if W.register(WEECHAT_SCRIPT_NAME, WEECHAT_SCRIPT_AUTHOR, + WEECHAT_SCRIPT_VERSION, WEECHAT_SCRIPT_LICENSE, + WEECHAT_SCRIPT_DESCRIPTION, 'matrix_unload_cb', ''): # TODO if this fails we should abort and unload the script. - matrix.globals.CONFIG = W.config_new( - "matrix", - "matrix_config_reload_cb", - "" - ) + matrix.globals.CONFIG = W.config_new("matrix", + "matrix_config_reload_cb", "") matrix_config_init(matrix.globals.CONFIG) matrix_config_read(matrix.globals.CONFIG) diff --git a/matrix/api.py b/matrix/api.py index c1a5531..5f25fca 100644 --- a/matrix/api.py +++ b/matrix/api.py @@ -52,17 +52,18 @@ class MessageType(Enum): class MatrixClient: + def __init__( self, - host, # type: str + host, # type: str access_token="", # type: str - user_agent="" # type: str + user_agent="" # type: str ): # type: (...) -> None self.host = host self.user_agent = user_agent self.access_token = access_token - self.txn_id = 0 # type: int + self.txn_id = 0 # type: int def _get_txn_id(self): txn_id = self.txn_id @@ -92,17 +93,13 @@ class MatrixClient: if sync_filter: query_parameters["filter"] = json.dumps( - sync_filter, - separators=(",", ":") - ) + sync_filter, separators=(",", ":")) if next_batch: query_parameters["since"] = next_batch path = ("{api}/sync?{query_params}").format( - api=MATRIX_API_PATH, - query_params=urlencode(query_parameters) - ) + api=MATRIX_API_PATH, query_params=urlencode(query_parameters)) return HttpRequest(RequestType.GET, self.host, path) @@ -110,10 +107,7 @@ class MatrixClient: # type: (str, str, str) -> HttpRequest query_parameters = {"access_token": self.access_token} - body = { - "msgtype": "m.text", - "body": content - } + body = {"msgtype": "m.text", "body": content} if formatted_content: body["format"] = "org.matrix.custom.html" @@ -160,14 +154,12 @@ class MatrixClient: return HttpRequest(RequestType.PUT, self.host, path, content) - def room_get_messages( - self, - room_id, - start_token, - end_token="", - limit=10, - direction='b' - ): + def room_get_messages(self, + room_id, + start_token, + end_token="", + limit=10, + direction='b'): query_parameters = { "access_token": self.access_token, "from": start_token, @@ -222,13 +214,15 @@ class MatrixClient: class MatrixMessage(): + def __init__( self, - message_type, # type: MessageType - request_func, # type: Callable[[...], HttpRequest] + message_type, # type: MessageType + request_func, # type: Callable[[...], HttpRequest] func_args, ): # type: (...) -> None + # yapf: disable self.type = message_type # type: MessageType self.request = None # type: HttpRequest @@ -241,13 +235,12 @@ class MatrixMessage(): self.event = None self.request = request_func(**func_args) + # yapf: enable def decode_body(self, server): try: self.decoded_response = json.loads( - self.response.body, - encoding='utf-8' - ) + self.response.body, encoding='utf-8') return (True, None) except Exception as error: return (False, error) @@ -268,33 +261,23 @@ class MatrixMessage(): class MatrixLoginMessage(MatrixMessage): + def __init__(self, client, user, password, device_name, device_id=None): - data = { - "user": user, - "password": password, - "device_name": device_name - } + data = {"user": user, "password": password, "device_name": device_name} if device_id: data["device_id"] = device_id - MatrixMessage.__init__( - self, - MessageType.LOGIN, - client.login, - data - ) + MatrixMessage.__init__(self, MessageType.LOGIN, client.login, data) def decode_body(self, server): - object_hook = partial( - MatrixEvents.MatrixLoginEvent.from_dict, - server - ) + object_hook = partial(MatrixEvents.MatrixLoginEvent.from_dict, server) return self._decode(server, object_hook) class MatrixSyncMessage(MatrixMessage): + def __init__(self, client, next_batch=None, limit=None): data = {} @@ -302,19 +285,13 @@ class MatrixSyncMessage(MatrixMessage): data["next_batch"] = next_batch if limit: - data["sync_filter"] = { - "room": {"timeline": {"limit": limit}} - } + data["sync_filter"] = {"room": {"timeline": {"limit": limit}}} - MatrixMessage.__init__( - self, - MessageType.SYNC, - client.sync, - data - ) + MatrixMessage.__init__(self, MessageType.SYNC, client.sync, data) class MatrixSendMessage(MatrixMessage): + def __init__(self, client, room_id, formatted_message): self.room_id = room_id self.formatted_message = formatted_message @@ -330,12 +307,8 @@ class MatrixSendMessage(MatrixMessage): if self.formatted_message.is_formatted: data["formatted_content"] = self.formatted_message.to_html() - MatrixMessage.__init__( - self, - MessageType.SEND, - client.room_send_message, - data - ) + MatrixMessage.__init__(self, MessageType.SEND, client.room_send_message, + data) def decode_body(self, server): object_hook = partial( @@ -349,21 +322,14 @@ class MatrixSendMessage(MatrixMessage): class MatrixTopicMessage(MatrixMessage): + def __init__(self, client, room_id, topic): self.room_id = room_id self.topic = topic - data = { - "room_id": self.room_id, - "topic": self.topic - } + data = {"room_id": self.room_id, "topic": self.topic} - MatrixMessage.__init__( - self, - MessageType.TOPIC, - client.room_topic, - data - ) + MatrixMessage.__init__(self, MessageType.TOPIC, client.room_topic, data) def decode_body(self, server): object_hook = partial( @@ -377,25 +343,19 @@ class MatrixTopicMessage(MatrixMessage): class MatrixRedactMessage(MatrixMessage): + def __init__(self, client, room_id, event_id, reason=None): self.room_id = room_id self.event_id = event_id self.reason = reason - data = { - "room_id": self.room_id, - "event_id": self.event_id - } + data = {"room_id": self.room_id, "event_id": self.event_id} if reason: data["reason"] = reason - MatrixMessage.__init__( - self, - MessageType.REDACT, - client.room_redact, - data - ) + MatrixMessage.__init__(self, MessageType.REDACT, client.room_redact, + data) def decode_body(self, server): object_hook = partial( @@ -409,6 +369,7 @@ class MatrixRedactMessage(MatrixMessage): class MatrixBacklogMessage(MatrixMessage): + def __init__(self, client, room_id, token, limit): self.room_id = room_id @@ -419,106 +380,81 @@ class MatrixBacklogMessage(MatrixMessage): "limit": limit } - MatrixMessage.__init__( - self, - MessageType.ROOM_MSG, - client.room_get_messages, - data - ) + MatrixMessage.__init__(self, MessageType.ROOM_MSG, + client.room_get_messages, data) def decode_body(self, server): - object_hook = partial( - MatrixEvents.MatrixBacklogEvent.from_dict, - server, - self.room_id) + object_hook = partial(MatrixEvents.MatrixBacklogEvent.from_dict, server, + self.room_id) return self._decode(server, object_hook) class MatrixJoinMessage(MatrixMessage): + def __init__(self, client, room_id): self.room_id = room_id data = {"room_id": self.room_id} - MatrixMessage.__init__( - self, - MessageType.JOIN, - client.room_join, - data - ) + MatrixMessage.__init__(self, MessageType.JOIN, client.room_join, data) def decode_body(self, server): - object_hook = partial( - MatrixEvents.MatrixJoinEvent.from_dict, - server, - self.room_id - ) + object_hook = partial(MatrixEvents.MatrixJoinEvent.from_dict, server, + self.room_id) return self._decode(server, object_hook) class MatrixPartMessage(MatrixMessage): + def __init__(self, client, room_id): self.room_id = room_id data = {"room_id": self.room_id} - MatrixMessage.__init__( - self, - MessageType.PART, - client.room_leave, - data - ) + MatrixMessage.__init__(self, MessageType.PART, client.room_leave, data) def decode_body(self, server): - object_hook = partial( - MatrixEvents.MatrixPartEvent.from_dict, - server, - self.room_id - ) + object_hook = partial(MatrixEvents.MatrixPartEvent.from_dict, server, + self.room_id) return self._decode(server, object_hook) class MatrixInviteMessage(MatrixMessage): + def __init__(self, client, room_id, user_id): self.room_id = room_id self.user_id = user_id - data = {"room_id": self.room_id, - "user_id": self.user_id} + data = {"room_id": self.room_id, "user_id": self.user_id} - MatrixMessage.__init__( - self, - MessageType.INVITE, - client.room_invite, - data - ) + MatrixMessage.__init__(self, MessageType.INVITE, client.room_invite, + data) def decode_body(self, server): - object_hook = partial( - MatrixEvents.MatrixInviteEvent.from_dict, - server, - self.room_id, - self.user_id - ) + object_hook = partial(MatrixEvents.MatrixInviteEvent.from_dict, server, + self.room_id, self.user_id) return self._decode(server, object_hook) class MatrixUser: + def __init__(self, name, display_name): - self.name = name # type: str + self.name = name # type: str self.display_name = display_name # type: str - self.power_level = 0 # type: int - self.nick_color = "" # type: str - self.prefix = "" # type: str + self.power_level = 0 # type: int + self.nick_color = "" # type: str + self.prefix = "" # type: str class MatrixRoom: + def __init__(self, room_id): # type: (str) -> None + # yapf: disable self.room_id = room_id # type: str self.alias = room_id # type: str self.topic = "" # type: str @@ -527,3 +463,4 @@ class MatrixRoom: self.prev_batch = "" # type: str self.users = dict() # type: Dict[str, MatrixUser] self.encrypted = False # type: bool + # yapf: enable diff --git a/matrix/colors.py b/matrix/colors.py index d9fc273..c4292d2 100644 --- a/matrix/colors.py +++ b/matrix/colors.py @@ -30,19 +30,15 @@ try: except ImportError: from html.parser import HTMLParser - -FormattedString = namedtuple( - 'FormattedString', - ['text', 'attributes'] -) +FormattedString = namedtuple('FormattedString', ['text', 'attributes']) class Formatted(): + def __init__(self, substrings): # type: (List[FormattedString]) -> None self.substrings = substrings - def is_formatted(self): # type: (Formatted) -> bool for string in self.substrings: @@ -58,7 +54,7 @@ class Formatted(): can be later converted to HTML or to a string for weechat's print functions """ - text = "" # type: str + text = "" # type: str substrings = [] # type: List[FormattedString] attributes = DEFAULT_ATRIBUTES.copy() @@ -154,24 +150,16 @@ class Formatted(): def add_attribute(string, name, value): if name == "bold" and value: return "{bold_on}{text}{bold_off}".format( - bold_on="", - text=string, - bold_off="") + bold_on="", text=string, bold_off="") elif name == "italic" and value: return "{italic_on}{text}{italic_off}".format( - italic_on="", - text=string, - italic_off="") + italic_on="", text=string, italic_off="") elif name == "underline" and value: return "{underline_on}{text}{underline_off}".format( - underline_on="", - text=string, - underline_off="") + underline_on="", text=string, underline_off="") elif name == "strikethrough" and value: return "{strike_on}{text}{strike_off}".format( - strike_on="", - text=string, - strike_off="") + strike_on="", text=string, strike_off="") elif name == "quote" and value: return "{quote_on}{text}{quote_off}".format( quote_on="
", @@ -180,8 +168,7 @@ class Formatted(): elif name == "fgcolor" and value: return "{color_on}{text}{color_off}".format( color_on="".format( - color=color_weechat_to_html(value) - ), + color=color_weechat_to_html(value)), text=string, color_off="") @@ -286,15 +273,14 @@ class MatrixHtmlParser(HTMLParser): # TODO bullets def __init__(self): HTMLParser.__init__(self) - self.text = "" # type: str + self.text = "" # type: str self.substrings = [] # type: List[FormattedString] self.attributes = DEFAULT_ATRIBUTES.copy() def _toggle_attribute(self, attribute): if self.text: self.substrings.append( - FormattedString(self.text, self.attributes.copy()) - ) + FormattedString(self.text, self.attributes.copy())) self.text = "" self.attributes[attribute] = not self.attributes[attribute] @@ -321,8 +307,7 @@ class MatrixHtmlParser(HTMLParser): if self.text: self.substrings.append( - FormattedString(self.text, self.attributes.copy()) - ) + FormattedString(self.text, self.attributes.copy())) self.text = "" self.attributes["fgcolor"] = color else: @@ -342,8 +327,7 @@ class MatrixHtmlParser(HTMLParser): elif tag == "font": if self.text: self.substrings.append( - FormattedString(self.text, self.attributes.copy()) - ) + FormattedString(self.text, self.attributes.copy())) self.text = "" self.attributes["fgcolor"] = None else: @@ -355,8 +339,7 @@ class MatrixHtmlParser(HTMLParser): def get_substrings(self): if self.text: self.substrings.append( - FormattedString(self.text, self.attributes.copy()) - ) + FormattedString(self.text, self.attributes.copy())) return self.substrings @@ -477,6 +460,7 @@ def color_line_to_weechat(color_string): # under the ISC license. # More info: https://github.com/tmux/tmux/blob/master/colour.c + def colour_dist_sq(R, G, B, r, g, b): # pylint: disable=invalid-name,too-many-arguments # type: (int, int, int, int, int, int) -> int @@ -546,21 +530,21 @@ def colour_find_rgb(r, g, b): def color_html_to_weechat(color): # type: (str) -> str first_16 = { - (0, 0, 0): "black", # 0 - (128, 0, 0): "red", # 1 - (0, 128, 0): "green", # 2 - (128, 128, 0): "brown", # 3 - (0, 0, 128): "blue", # 4 - (128, 0, 128): "magenta", # 5 - (0, 128, 128): "cyan", # 6 - (192, 192, 192): "default", # 7 - (128, 128, 128): "gray", # 8 - (255, 0, 0): "lightred", # 9 - (0, 255, 0): "lightgreen", # 11 - (255, 255, 0): "yellow", # 12 - (0, 0, 255): "lightblue", # 13 - (255, 0, 255): "lightmagenta", # 14 - (0, 255, 255): "lightcyan", # 15 + (0, 0, 0): "black", # 0 + (128, 0, 0): "red", # 1 + (0, 128, 0): "green", # 2 + (128, 128, 0): "brown", # 3 + (0, 0, 128): "blue", # 4 + (128, 0, 128): "magenta", # 5 + (0, 128, 128): "cyan", # 6 + (192, 192, 192): "default", # 7 + (128, 128, 128): "gray", # 8 + (255, 0, 0): "lightred", # 9 + (0, 255, 0): "lightgreen", # 11 + (255, 255, 0): "yellow", # 12 + (0, 0, 255): "lightblue", # 13 + (255, 0, 255): "lightmagenta", # 14 + (0, 255, 255): "lightcyan", # 15 } try: @@ -577,23 +561,23 @@ def color_html_to_weechat(color): def color_weechat_to_html(color): # type: (str) -> str first_16 = { - "black": "black", # 0 - "red": "maroon", # 1 - "green": "green", # 2 - "brown": "olive", # 3 - "blue": "navy", # 4 - "magenta": "purple", # 5 - "cyan": "teal", # 6 - "default": "silver", # 7 - "gray": "grey", # 8 - "lightred": "red", # 9 - "lightgreen": "lime", # 11 - "yellow": "yellow", # 12 - "lightblue": "fuchsia", # 13 - "lightmagenta": "aqua", # 14 - "lightcyan": "white", # 15 + "black": "black", # 0 + "red": "maroon", # 1 + "green": "green", # 2 + "brown": "olive", # 3 + "blue": "navy", # 4 + "magenta": "purple", # 5 + "cyan": "teal", # 6 + "default": "silver", # 7 + "gray": "grey", # 8 + "lightred": "red", # 9 + "lightgreen": "lime", # 11 + "yellow": "yellow", # 12 + "lightblue": "fuchsia", # 13 + "lightmagenta": "aqua", # 14 + "lightcyan": "white", # 15 } - + #yapf: disable hex_colors = { "0": "#000000", "1": "#800000", @@ -852,6 +836,7 @@ def color_weechat_to_html(color): "254": "#e4e4e4", "255": "#eeeeee" } + # yapf: enable if color in first_16: return first_16[color] diff --git a/matrix/http.py b/matrix/http.py index 8638f3e..8f67b8e 100644 --- a/matrix/http.py +++ b/matrix/http.py @@ -29,12 +29,14 @@ class RequestType(Enum): class HttpResponse: + def __init__(self, status, headers, body): - self.status = status # type: int + self.status = status # type: int self.headers = headers # type: Dict[str, str] - self.body = body # type: bytes + self.body = body # type: bytes +# yapf: disable class HttpRequest: def __init__( self, @@ -52,11 +54,13 @@ class HttpRequest: accept_header = 'Accept: */*' # type: str end_separator = '\r\n' # type: str payload = "" # type: str + # yapf: enable if request_type == RequestType.GET: get = 'GET {location} HTTP/1.1'.format(location=location) - request_list = [get, host_header, - user_agent, accept_header, end_separator] + request_list = [ + get, host_header, user_agent, accept_header, end_separator + ] elif (request_type == RequestType.POST or request_type == RequestType.PUT): @@ -69,18 +73,16 @@ class HttpRequest: method = "PUT" request_line = '{method} {location} HTTP/1.1'.format( - method=method, - location=location - ) + method=method, location=location) type_header = 'Content-Type: application/x-www-form-urlencoded' length_header = 'Content-Length: {length}'.format( - length=len(json_data) - ) + length=len(json_data)) - request_list = [request_line, host_header, - user_agent, accept_header, - length_header, type_header, end_separator] + request_list = [ + request_line, host_header, user_agent, accept_header, + length_header, type_header, end_separator + ] payload = json_data request = '\r\n'.join(request_list) diff --git a/matrix/server.py b/matrix/server.py index 622c5cc..d2b9f13 100644 --- a/matrix/server.py +++ b/matrix/server.py @@ -14,7 +14,6 @@ # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - from __future__ import unicode_literals from builtins import str, bytes @@ -26,12 +25,8 @@ from collections import deque from http_parser.pyparser import HttpParser from matrix.plugin_options import Option, DebugType -from matrix.utils import ( - key_from_value, - prnt_debug, - server_buffer_prnt, - create_server_buffer -) +from matrix.utils import (key_from_value, prnt_debug, server_buffer_prnt, + create_server_buffer) from matrix.utf import utf8_decode from matrix.globals import W, SERVERS, OPTIONS from matrix.api import MatrixClient, MatrixSyncMessage, MatrixLoginMessage @@ -41,6 +36,7 @@ class MatrixServer: # pylint: disable=too-many-instance-attributes def __init__(self, name, config_file): # type: (str, weechat.config) -> None + # yapf: disable self.name = name # type: str self.user_id = "" self.address = "" # type: str @@ -91,43 +87,27 @@ class MatrixServer: self.ignore_event_list = [] # type: List[str] self._create_options(config_file) + # yapf: enable def _create_options(self, config_file): options = [ - Option( - 'autoconnect', 'boolean', '', 0, 0, 'off', - ( - "automatically connect to the matrix server when weechat " - "is starting" - ) - ), - Option( - 'address', 'string', '', 0, 0, '', - "Hostname or IP address for the server" - ), - Option( - 'port', 'integer', '', 0, 65535, '8448', - "Port for the server" - ), - Option( - 'ssl_verify', 'boolean', '', 0, 0, 'on', - ( - "Check that the SSL connection is fully trusted" - ) - ), - Option( - 'username', 'string', '', 0, 0, '', - "Username to use on server" - ), + Option('autoconnect', 'boolean', '', 0, 0, 'off', + ("automatically connect to the matrix server when weechat " + "is starting")), + Option('address', 'string', '', 0, 0, '', + "Hostname or IP address for the server"), + Option('port', 'integer', '', 0, 65535, '8448', + "Port for the server"), + Option('ssl_verify', 'boolean', '', 0, 0, 'on', + ("Check that the SSL connection is fully trusted")), + Option('username', 'string', '', 0, 0, '', + "Username to use on server"), Option( 'password', 'string', '', 0, 0, '', ("Password for server (note: content is evaluated, see /help " - "eval)") - ), - Option( - 'device_name', 'string', '', 0, 0, 'Weechat Matrix', - "Device name to use while logging in to the matrix server" - ), + "eval)")), + Option('device_name', 'string', '', 0, 0, 'Weechat Matrix', + "Device name to use while logging in to the matrix server"), ] section = W.config_search_section(config_file, 'server') @@ -137,10 +117,10 @@ class MatrixServer: server=self.name, option=option.name) self.options[option.name] = W.config_new_option( - config_file, section, option_name, - option.type, option.description, option.string_values, - option.min, option.max, option.value, option.value, 0, "", - "", "matrix_config_server_change_cb", self.name, "", "") + config_file, section, option_name, option.type, + option.description, option.string_values, option.min, + option.max, option.value, option.value, 0, "", "", + "matrix_config_server_change_cb", self.name, "", "") def reset_parser(self): self.http_parser = HttpParser() @@ -190,8 +170,7 @@ class MatrixServer: prnt_debug(DebugType.MESSAGING, self, ("{prefix} Failed sending message of type {t}. " "Adding to queue").format( - prefix=W.prefix("error"), - t=message.type)) + prefix=W.prefix("error"), t=message.type)) self.send_queue.append(message) def try_send(self, message): @@ -206,12 +185,7 @@ class MatrixServer: sent = sock.send(message[total_sent:]) except ssl.SSLWantWriteError: - hook = W.hook_fd( - sock.fileno(), - 0, 1, 0, - "send_cb", - self.name - ) + hook = W.hook_fd(sock.fileno(), 0, 1, 0, "send_cb", self.name) self.send_fd_hook = hook self.send_buffer = message[total_sent:] return True @@ -225,14 +199,12 @@ class MatrixServer: error_message = ("{prefix}Error while writing to " "socket: {error}").format( - prefix=W.prefix("network"), - error=strerr) + prefix=W.prefix("network"), error=strerr) server_buffer_prnt(self, error_message) server_buffer_prnt( - self, - ("{prefix}matrix: disconnecting from server...").format( - prefix=W.prefix("network"))) + self, ("{prefix}matrix: disconnecting from server..." + ).format(prefix=W.prefix("network"))) self.disconnect() return False @@ -245,9 +217,8 @@ class MatrixServer: "{prefix}matrix: Error while writing to socket".format( prefix=W.prefix("network"))) server_buffer_prnt( - self, - ("{prefix}matrix: disconnecting from server...").format( - prefix=W.prefix("network"))) + self, ("{prefix}matrix: disconnecting from server..." + ).format(prefix=W.prefix("network"))) self.disconnect() return False @@ -269,7 +240,6 @@ class MatrixServer: self.send_buffer = b"" self.current_message = None - def send(self, message): # type: (MatrixServer, MatrixMessage) -> bool if self.current_message: @@ -287,8 +257,8 @@ class MatrixServer: return True def reconnect(self): - message = ("{prefix}matrix: reconnecting to server...").format( - prefix=W.prefix("network")) + message = ("{prefix}matrix: reconnecting to server..." + ).format(prefix=W.prefix("network")) server_buffer_prnt(self, message) @@ -309,8 +279,7 @@ class MatrixServer: message = ("{prefix}matrix: reconnecting to server in {t} " "seconds").format( - prefix=W.prefix("network"), - t=self.reconnect_delay) + prefix=W.prefix("network"), t=self.reconnect_delay) server_buffer_prnt(self, message) @@ -347,8 +316,8 @@ class MatrixServer: self.reconnect_time = None if self.server_buffer: - message = ("{prefix}matrix: disconnected from server").format( - prefix=W.prefix("network")) + message = ("{prefix}matrix: disconnected from server" + ).format(prefix=W.prefix("network")) server_buffer_prnt(self, message) if reconnect: @@ -375,13 +344,8 @@ class MatrixServer: create_server_buffer(self) if not self.timer_hook: - self.timer_hook = W.hook_timer( - 1 * 1000, - 0, - 0, - "matrix_timer_cb", - self.name - ) + self.timer_hook = W.hook_timer(1 * 1000, 0, 0, "matrix_timer_cb", + self.name) ssl_message = " (SSL)" if self.ssl_context.check_hostname else "" @@ -394,35 +358,26 @@ class MatrixServer: W.prnt(self.server_buffer, message) - W.hook_connect("", self.address, self.port, 1, 0, "", - "connect_cb", self.name) + W.hook_connect("", self.address, self.port, 1, 0, "", "connect_cb", + self.name) return True def sync(self): - message = MatrixSyncMessage( - self.client, - self.next_batch, - OPTIONS.sync_limit - ) + message = MatrixSyncMessage(self.client, self.next_batch, + OPTIONS.sync_limit) self.send_queue.append(message) def login(self): # type: (MatrixServer) -> None - message = MatrixLoginMessage( - self.client, - self.user, - self.password, - self.device_name - ) + message = MatrixLoginMessage(self.client, self.user, self.password, + self.device_name) self.send_or_queue(message) @utf8_decode -def matrix_config_server_read_cb( - data, config_file, section, - option_name, value -): +def matrix_config_server_read_cb(data, config_file, section, option_name, + value): return_code = W.WEECHAT_CONFIG_OPTION_SET_ERROR @@ -479,8 +434,7 @@ def matrix_timer_cb(server_name, remaining_calls): current_time = time.time() - if ((not server.connected) and - server.reconnect_time and + if ((not server.connected) and server.reconnect_time and current_time >= (server.reconnect_time + server.reconnect_delay)): server.reconnect() return W.WEECHAT_RC_OK @@ -504,9 +458,10 @@ def matrix_timer_cb(server_name, remaining_calls): while server.send_queue: message = server.send_queue.popleft() - prnt_debug(DebugType.MESSAGING, server, - ("Timer hook found message of type {t} in queue. Sending " - "out.".format(t=message.type))) + prnt_debug( + DebugType.MESSAGING, + server, ("Timer hook found message of type {t} in queue. Sending " + "out.".format(t=message.type))) if not server.send(message): # We got an error while sending the last message return the message