Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Commit

Permalink
Run Black.
Browse files Browse the repository at this point in the history
  • Loading branch information
hawkowl committed Jun 17, 2019
1 parent aecc113 commit 043d2fb
Show file tree
Hide file tree
Showing 372 changed files with 9,115 additions and 10,374 deletions.
309 changes: 190 additions & 119 deletions contrib/cmdclient/console.py

Large diffs are not rendered by default.

38 changes: 15 additions & 23 deletions contrib/cmdclient/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,7 @@ def __init__(self):
@defer.inlineCallbacks
def put_json(self, url, data):
response = yield self._create_put_request(
url,
data,
headers_dict={"Content-Type": ["application/json"]}
url, data, headers_dict={"Content-Type": ["application/json"]}
)
body = yield readBody(response)
defer.returnValue((response.code, body))
Expand All @@ -95,40 +93,34 @@ def _create_put_request(self, url, json_data, headers_dict={}):
"""

if "Content-Type" not in headers_dict:
raise defer.error(
RuntimeError("Must include Content-Type header for PUTs"))
raise defer.error(RuntimeError("Must include Content-Type header for PUTs"))

return self._create_request(
"PUT",
url,
producer=_JsonProducer(json_data),
headers_dict=headers_dict
"PUT", url, producer=_JsonProducer(json_data), headers_dict=headers_dict
)

def _create_get_request(self, url, headers_dict={}):
""" Wrapper of _create_request to issue a GET request
"""
return self._create_request(
"GET",
url,
headers_dict=headers_dict
)
return self._create_request("GET", url, headers_dict=headers_dict)

@defer.inlineCallbacks
def do_request(self, method, url, data=None, qparams=None, jsonreq=True, headers={}):
def do_request(
self, method, url, data=None, qparams=None, jsonreq=True, headers={}
):
if qparams:
url = "%s?%s" % (url, urllib.urlencode(qparams, True))

if jsonreq:
prod = _JsonProducer(data)
headers['Content-Type'] = ["application/json"];
headers["Content-Type"] = ["application/json"]
else:
prod = _RawProducer(data)

if method in ["POST", "PUT"]:
response = yield self._create_request(method, url,
producer=prod,
headers_dict=headers)
response = yield self._create_request(
method, url, producer=prod, headers_dict=headers
)
else:
response = yield self._create_request(method, url)

Expand All @@ -155,10 +147,7 @@ def _create_request(self, method, url, producer=None, headers_dict={}):
while True:
try:
response = yield self.agent.request(
method,
url.encode("UTF8"),
Headers(headers_dict),
producer
method, url.encode("UTF8"), Headers(headers_dict), producer
)
break
except Exception as e:
Expand All @@ -179,6 +168,7 @@ def sleep(self, seconds):
reactor.callLater(seconds, d.callback, seconds)
return d


class _RawProducer(object):
def __init__(self, data):
self.data = data
Expand All @@ -195,9 +185,11 @@ def pauseProducing(self):
def stopProducing(self):
pass


class _JsonProducer(object):
""" Used by the twisted http client to create the HTTP body from json
"""

def __init__(self, jsn):
self.data = jsn
self.body = json.dumps(jsn).encode("utf8")
Expand Down
36 changes: 17 additions & 19 deletions contrib/experiments/cursesio.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@
from twisted.internet import reactor


class CursesStdIO():
class CursesStdIO:
def __init__(self, stdscr, callback=None):
self.statusText = "Synapse test app -"
self.searchText = ''
self.searchText = ""
self.stdscr = stdscr

self.logLine = ''
self.logLine = ""

self.callback = callback

Expand Down Expand Up @@ -71,8 +71,7 @@ def redraw(self):
i = 0
index = len(self.lines) - 1
while i < (self.rows - 3) and index >= 0:
self.stdscr.addstr(self.rows - 3 - i, 0, self.lines[index],
curses.A_NORMAL)
self.stdscr.addstr(self.rows - 3 - i, 0, self.lines[index], curses.A_NORMAL)
i = i + 1
index = index - 1

Expand All @@ -85,15 +84,13 @@ def paintStatus(self, text):
raise RuntimeError("TextTooLongError")

self.stdscr.addstr(
self.rows - 2, 0,
text + ' ' * (self.cols - len(text)),
curses.A_STANDOUT)
self.rows - 2, 0, text + " " * (self.cols - len(text)), curses.A_STANDOUT
)

def printLogLine(self, text):
self.stdscr.addstr(
0, 0,
text + ' ' * (self.cols - len(text)),
curses.A_STANDOUT)
0, 0, text + " " * (self.cols - len(text)), curses.A_STANDOUT
)

def doRead(self):
""" Input is ready! """
Expand All @@ -105,7 +102,7 @@ def doRead(self):

elif c == curses.KEY_ENTER or c == 10:
text = self.searchText
self.searchText = ''
self.searchText = ""

self.print_line(">> %s" % text)

Expand All @@ -122,11 +119,13 @@ def doRead(self):
return
self.searchText = self.searchText + chr(c)

self.stdscr.addstr(self.rows - 1, 0,
self.searchText + (' ' * (
self.cols - len(self.searchText) - 2)))
self.stdscr.addstr(
self.rows - 1,
0,
self.searchText + (" " * (self.cols - len(self.searchText) - 2)),
)

self.paintStatus(self.statusText + ' %d' % len(self.searchText))
self.paintStatus(self.statusText + " %d" % len(self.searchText))
self.stdscr.move(self.rows - 1, len(self.searchText))
self.stdscr.refresh()

Expand All @@ -143,7 +142,6 @@ def close(self):


class Callback(object):

def __init__(self, stdio):
self.stdio = stdio

Expand All @@ -152,7 +150,7 @@ def on_line(self, text):


def main(stdscr):
screen = CursesStdIO(stdscr) # create Screen object
screen = CursesStdIO(stdscr) # create Screen object

callback = Callback(screen)

Expand All @@ -164,5 +162,5 @@ def main(stdscr):
screen.close()


if __name__ == '__main__':
if __name__ == "__main__":
curses.wrapper(main)
81 changes: 39 additions & 42 deletions contrib/experiments/test_messaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,15 @@
"""


from synapse.federation import (
ReplicationHandler
)
from synapse.federation import ReplicationHandler

from synapse.federation.units import Pdu

from synapse.util import origin_from_ucid

from synapse.app.homeserver import SynapseHomeServer

#from synapse.util.logutils import log_function
# from synapse.util.logutils import log_function

from twisted.internet import reactor, defer
from twisted.python import log
Expand Down Expand Up @@ -83,7 +81,7 @@ def on_line(self, line):
room_name, = m.groups()
self.print_line("%s joining %s" % (self.user, room_name))
self.server.join_room(room_name, self.user, self.user)
#self.print_line("OK.")
# self.print_line("OK.")
return

m = re.match("^invite (\S+) (\S+)$", line)
Expand All @@ -92,7 +90,7 @@ def on_line(self, line):
room_name, invitee = m.groups()
self.print_line("%s invited to %s" % (invitee, room_name))
self.server.invite_to_room(room_name, self.user, invitee)
#self.print_line("OK.")
# self.print_line("OK.")
return

m = re.match("^send (\S+) (.*)$", line)
Expand All @@ -101,7 +99,7 @@ def on_line(self, line):
room_name, body = m.groups()
self.print_line("%s send to %s" % (self.user, room_name))
self.server.send_message(room_name, self.user, body)
#self.print_line("OK.")
# self.print_line("OK.")
return

m = re.match("^backfill (\S+)$", line)
Expand All @@ -125,7 +123,6 @@ def print_log(self, text):


class IOLoggerHandler(logging.Handler):

def __init__(self, io):
logging.Handler.__init__(self)
self.io = io
Expand All @@ -142,6 +139,7 @@ class Room(object):
""" Used to store (in memory) the current membership state of a room, and
which home servers we should send PDUs associated with the room to.
"""

def __init__(self, room_name):
self.room_name = room_name
self.invited = set()
Expand Down Expand Up @@ -175,6 +173,7 @@ class HomeServer(ReplicationHandler):
""" A very basic home server implentation that allows people to join a
room and then invite other people.
"""

def __init__(self, server_name, replication_layer, output):
self.server_name = server_name
self.replication_layer = replication_layer
Expand All @@ -197,46 +196,43 @@ def on_receive_pdu(self, pdu):
elif pdu.content["membership"] == "invite":
self._on_invite(pdu.origin, pdu.context, pdu.state_key)
else:
self.output.print_line("#%s (unrec) %s = %s" %
(pdu.context, pdu.pdu_type, json.dumps(pdu.content))
self.output.print_line(
"#%s (unrec) %s = %s"
% (pdu.context, pdu.pdu_type, json.dumps(pdu.content))
)

#def on_state_change(self, pdu):
##self.output.print_line("#%s (state) %s *** %s" %
##(pdu.context, pdu.state_key, pdu.pdu_type)
##)
# def on_state_change(self, pdu):
##self.output.print_line("#%s (state) %s *** %s" %
##(pdu.context, pdu.state_key, pdu.pdu_type)
##)

#if "joinee" in pdu.content:
#self._on_join(pdu.context, pdu.content["joinee"])
#elif "invitee" in pdu.content:
#self._on_invite(pdu.origin, pdu.context, pdu.content["invitee"])
# if "joinee" in pdu.content:
# self._on_join(pdu.context, pdu.content["joinee"])
# elif "invitee" in pdu.content:
# self._on_invite(pdu.origin, pdu.context, pdu.content["invitee"])

def _on_message(self, pdu):
""" We received a message
"""
self.output.print_line("#%s %s %s" %
(pdu.context, pdu.content["sender"], pdu.content["body"])
)
self.output.print_line(
"#%s %s %s" % (pdu.context, pdu.content["sender"], pdu.content["body"])
)

def _on_join(self, context, joinee):
""" Someone has joined a room, either a remote user or a local user
"""
room = self._get_or_create_room(context)
room.add_participant(joinee)

self.output.print_line("#%s %s %s" %
(context, joinee, "*** JOINED")
)
self.output.print_line("#%s %s %s" % (context, joinee, "*** JOINED"))

def _on_invite(self, origin, context, invitee):
""" Someone has been invited
"""
room = self._get_or_create_room(context)
room.add_invited(invitee)

self.output.print_line("#%s %s %s" %
(context, invitee, "*** INVITED")
)
self.output.print_line("#%s %s %s" % (context, invitee, "*** INVITED"))

if not room.have_got_metadata and origin is not self.server_name:
logger.debug("Get room state")
Expand Down Expand Up @@ -272,14 +268,14 @@ def join_room(self, room_name, sender, joinee):

try:
pdu = Pdu.create_new(
context=room_name,
pdu_type="sy.room.member",
is_state=True,
state_key=joinee,
content={"membership": "join"},
origin=self.server_name,
destinations=destinations,
)
context=room_name,
pdu_type="sy.room.member",
is_state=True,
state_key=joinee,
content={"membership": "join"},
origin=self.server_name,
destinations=destinations,
)
yield self.replication_layer.send_pdu(pdu)
except Exception as e:
logger.exception(e)
Expand Down Expand Up @@ -318,21 +314,21 @@ def backfill(self, room_name, limit=5):
return self.replication_layer.backfill(dest, room_name, limit)

def _get_room_remote_servers(self, room_name):
return [i for i in self.joined_rooms.setdefault(room_name,).servers]
return [i for i in self.joined_rooms.setdefault(room_name).servers]

def _get_or_create_room(self, room_name):
return self.joined_rooms.setdefault(room_name, Room(room_name))

def get_servers_for_context(self, context):
return defer.succeed(
self.joined_rooms.setdefault(context, Room(context)).servers
)
self.joined_rooms.setdefault(context, Room(context)).servers
)


def main(stdscr):
parser = argparse.ArgumentParser()
parser.add_argument('user', type=str)
parser.add_argument('-v', '--verbose', action='count')
parser.add_argument("user", type=str)
parser.add_argument("-v", "--verbose", action="count")
args = parser.parse_args()

user = args.user
Expand All @@ -342,8 +338,9 @@ def main(stdscr):

root_logger = logging.getLogger()

formatter = logging.Formatter('%(asctime)s - %(name)s - %(lineno)d - '
'%(levelname)s - %(message)s')
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(lineno)d - " "%(levelname)s - %(message)s"
)
if not os.path.exists("logs"):
os.makedirs("logs")
fh = logging.FileHandler("logs/%s" % user)
Expand Down
Loading

0 comments on commit 043d2fb

Please sign in to comment.