black: Reformat without skipping string normalization.

This commit is contained in:
PIG208 2021-05-28 17:05:11 +08:00 committed by Tim Abbott
parent fba21bb00d
commit 6f3f9bf7e4
178 changed files with 5242 additions and 5242 deletions

View file

@ -62,7 +62,7 @@ def stream_to_room(stream: str) -> str:
def jid_to_zulip(jid: JID) -> str:
suffix = ''
suffix = ""
if not jid.username.endswith("-bot"):
suffix = options.zulip_email_suffix
return "%s%s@%s" % (jid.username, suffix, options.zulip_domain)
@ -94,10 +94,10 @@ class JabberToZulipBot(ClientXMPP):
self.zulip = None
self.use_ipv6 = False
self.register_plugin('xep_0045') # Jabber chatrooms
self.register_plugin('xep_0199') # XMPP Ping
self.register_plugin("xep_0045") # Jabber chatrooms
self.register_plugin("xep_0199") # XMPP Ping
def set_zulip_client(self, zulipToJabberClient: 'ZulipToJabberBot') -> None:
def set_zulip_client(self, zulipToJabberClient: "ZulipToJabberBot") -> None:
self.zulipToJabber = zulipToJabberClient
def session_start(self, event: Dict[str, Any]) -> None:
@ -112,7 +112,7 @@ class JabberToZulipBot(ClientXMPP):
logging.debug("Joining " + room)
self.rooms.add(room)
muc_jid = JID(local=room, domain=options.conference_domain)
xep0045 = self.plugin['xep_0045']
xep0045 = self.plugin["xep_0045"]
try:
xep0045.joinMUC(muc_jid, self.nick, wait=True)
except InvalidJID:
@ -137,7 +137,7 @@ class JabberToZulipBot(ClientXMPP):
logging.debug("Leaving " + room)
self.rooms.remove(room)
muc_jid = JID(local=room, domain=options.conference_domain)
self.plugin['xep_0045'].leaveMUC(muc_jid, self.nick)
self.plugin["xep_0045"].leaveMUC(muc_jid, self.nick)
def message(self, msg: JabberMessage) -> Any:
try:
@ -152,7 +152,7 @@ class JabberToZulipBot(ClientXMPP):
logging.exception("Error forwarding Jabber => Zulip")
def private(self, msg: JabberMessage) -> None:
if options.mode == 'public' or msg['thread'] == '\u1FFFE':
if options.mode == "public" or msg["thread"] == "\u1FFFE":
return
sender = jid_to_zulip(msg["from"])
recipient = jid_to_zulip(msg["to"])
@ -168,13 +168,13 @@ class JabberToZulipBot(ClientXMPP):
logging.error(str(ret))
def group(self, msg: JabberMessage) -> None:
if options.mode == 'personal' or msg["thread"] == '\u1FFFE':
if options.mode == "personal" or msg["thread"] == "\u1FFFE":
return
subject = msg["subject"]
if len(subject) == 0:
subject = "(no topic)"
stream = room_to_stream(msg['from'].local)
stream = room_to_stream(msg["from"].local)
sender_nick = msg.get_mucnick()
if not sender_nick:
# Messages from the room itself have no nickname. We should not try
@ -195,9 +195,9 @@ class JabberToZulipBot(ClientXMPP):
logging.error(str(ret))
def nickname_to_jid(self, room: str, nick: str) -> JID:
jid = self.plugin['xep_0045'].getJidProperty(room, nick, "jid")
if jid is None or jid == '':
return JID(local=nick.replace(' ', ''), domain=self.boundjid.domain)
jid = self.plugin["xep_0045"].getJidProperty(room, nick, "jid")
if jid is None or jid == "":
return JID(local=nick.replace(" ", ""), domain=self.boundjid.domain)
else:
return jid
@ -211,59 +211,59 @@ class ZulipToJabberBot:
self.jabber = client
def process_event(self, event: Dict[str, Any]) -> None:
if event['type'] == 'message':
if event["type"] == "message":
message = event["message"]
if message['sender_email'] != self.client.email:
if message["sender_email"] != self.client.email:
return
try:
if message['type'] == 'stream':
if message["type"] == "stream":
self.stream_message(message)
elif message['type'] == 'private':
elif message["type"] == "private":
self.private_message(message)
except Exception:
logging.exception("Exception forwarding Zulip => Jabber")
elif event['type'] == 'subscription':
elif event["type"] == "subscription":
self.process_subscription(event)
def stream_message(self, msg: Dict[str, str]) -> None:
assert self.jabber is not None
stream = msg['display_recipient']
stream = msg["display_recipient"]
if not stream.endswith("/xmpp"):
return
room = stream_to_room(stream)
jabber_recipient = JID(local=room, domain=options.conference_domain)
outgoing = self.jabber.make_message(
mto=jabber_recipient, mbody=msg['content'], mtype='groupchat'
mto=jabber_recipient, mbody=msg["content"], mtype="groupchat"
)
outgoing['thread'] = '\u1FFFE'
outgoing["thread"] = "\u1FFFE"
outgoing.send()
def private_message(self, msg: Dict[str, Any]) -> None:
assert self.jabber is not None
for recipient in msg['display_recipient']:
for recipient in msg["display_recipient"]:
if recipient["email"] == self.client.email:
continue
if not recipient["is_mirror_dummy"]:
continue
recip_email = recipient['email']
recip_email = recipient["email"]
jabber_recipient = zulip_to_jid(recip_email, self.jabber.boundjid.domain)
outgoing = self.jabber.make_message(
mto=jabber_recipient, mbody=msg['content'], mtype='chat'
mto=jabber_recipient, mbody=msg["content"], mtype="chat"
)
outgoing['thread'] = '\u1FFFE'
outgoing["thread"] = "\u1FFFE"
outgoing.send()
def process_subscription(self, event: Dict[str, Any]) -> None:
assert self.jabber is not None
if event['op'] == 'add':
streams = [s['name'].lower() for s in event['subscriptions']]
if event["op"] == "add":
streams = [s["name"].lower() for s in event["subscriptions"]]
streams = [s for s in streams if s.endswith("/xmpp")]
for stream in streams:
self.jabber.join_muc(stream_to_room(stream))
if event['op'] == 'remove':
streams = [s['name'].lower() for s in event['subscriptions']]
if event["op"] == "remove":
streams = [s["name"].lower() for s in event["subscriptions"]]
streams = [s for s in streams if s.endswith("/xmpp")]
for stream in streams:
self.jabber.leave_muc(stream_to_room(stream))
@ -277,14 +277,14 @@ def get_rooms(zulipToJabber: ZulipToJabberBot) -> List[str]:
sys.exit("Could not get initial list of Zulip %s" % (key,))
return ret[key]
if options.mode == 'public':
if options.mode == "public":
stream_infos = get_stream_infos("streams", zulipToJabber.client.get_streams)
else:
stream_infos = get_stream_infos("subscriptions", zulipToJabber.client.get_subscriptions)
rooms = [] # type: List[str]
for stream_info in stream_infos:
stream = stream_info['name']
stream = stream_info["name"]
if stream.endswith("/xmpp"):
rooms.append(stream_to_room(stream))
return rooms
@ -295,20 +295,20 @@ def config_error(msg: str) -> None:
sys.exit(2)
if __name__ == '__main__':
if __name__ == "__main__":
parser = optparse.OptionParser(
epilog='''Most general and Jabber configuration options may also be specified in the
epilog="""Most general and Jabber configuration options may also be specified in the
zulip configuration file under the jabber_mirror section (exceptions are noted
in their help sections). Keys have the same name as options with hyphens
replaced with underscores. Zulip configuration options go in the api section,
as normal.'''.replace(
as normal.""".replace(
"\n", " "
)
)
parser.add_option(
'--mode',
"--mode",
default=None,
action='store',
action="store",
help='''Which mode to run in. Valid options are "personal" and "public". In
"personal" mode, the mirror uses an individual users' credentials and mirrors
all messages they send on Zulip to Jabber and all private Jabber messages to
@ -319,33 +319,33 @@ user and mirrors messages sent to Jabber rooms to Zulip. Defaults to
),
)
parser.add_option(
'--zulip-email-suffix',
"--zulip-email-suffix",
default=None,
action='store',
help='''Add the specified suffix to the local part of email addresses constructed
action="store",
help="""Add the specified suffix to the local part of email addresses constructed
from JIDs and nicks before sending requests to the Zulip server, and remove the
suffix before sending requests to the Jabber server. For example, specifying
"+foo" will cause messages that are sent to the "bar" room by nickname "qux" to
be mirrored to the "bar/xmpp" stream in Zulip by user "qux+foo@example.com". This
option does not affect login credentials.'''.replace(
option does not affect login credentials.""".replace(
"\n", " "
),
)
parser.add_option(
'-d',
'--debug',
help='set logging to DEBUG. Can not be set via config file.',
action='store_const',
dest='log_level',
"-d",
"--debug",
help="set logging to DEBUG. Can not be set via config file.",
action="store_const",
dest="log_level",
const=logging.DEBUG,
default=logging.INFO,
)
jabber_group = optparse.OptionGroup(parser, "Jabber configuration")
jabber_group.add_option(
'--jid',
"--jid",
default=None,
action='store',
action="store",
help="Your Jabber JID. If a resource is specified, "
"it will be used as the nickname when joining MUCs. "
"Specifying the nickname is mostly useful if you want "
@ -353,27 +353,27 @@ option does not affect login credentials.'''.replace(
"from a dedicated account.",
)
jabber_group.add_option(
'--jabber-password', default=None, action='store', help="Your Jabber password"
"--jabber-password", default=None, action="store", help="Your Jabber password"
)
jabber_group.add_option(
'--conference-domain',
"--conference-domain",
default=None,
action='store',
action="store",
help="Your Jabber conference domain (E.g. conference.jabber.example.com). "
"If not specifed, \"conference.\" will be prepended to your JID's domain.",
'If not specifed, "conference." will be prepended to your JID\'s domain.',
)
jabber_group.add_option('--no-use-tls', default=None, action='store_true')
jabber_group.add_option("--no-use-tls", default=None, action="store_true")
jabber_group.add_option(
'--jabber-server-address',
"--jabber-server-address",
default=None,
action='store',
action="store",
help="The hostname of your Jabber server. This is only needed if "
"your server is missing SRV records",
)
jabber_group.add_option(
'--jabber-server-port',
default='5222',
action='store',
"--jabber-server-port",
default="5222",
action="store",
help="The port of your Jabber server. This is only needed if "
"your server is missing SRV records",
)
@ -382,7 +382,7 @@ option does not affect login credentials.'''.replace(
parser.add_option_group(zulip.generate_option_group(parser, "zulip-"))
(options, args) = parser.parse_args()
logging.basicConfig(level=options.log_level, format='%(levelname)-8s %(message)s')
logging.basicConfig(level=options.log_level, format="%(levelname)-8s %(message)s")
if options.zulip_config_file is None:
default_config_file = zulip.get_default_config_filename()
@ -422,9 +422,9 @@ option does not affect login credentials.'''.replace(
options.mode = "personal"
if options.zulip_email_suffix is None:
options.zulip_email_suffix = ''
options.zulip_email_suffix = ""
if options.mode not in ('public', 'personal'):
if options.mode not in ("public", "personal"):
config_error("Bad value for --mode: must be one of 'public' or 'personal'")
if None in (options.jid, options.jabber_password):
@ -437,7 +437,7 @@ option does not affect login credentials.'''.replace(
zulip.init_from_options(options, "JabberMirror/" + __version__)
)
# This won't work for open realms that don't have a consistent domain
options.zulip_domain = zulipToJabber.client.email.partition('@')[-1]
options.zulip_domain = zulipToJabber.client.email.partition("@")[-1]
try:
jid = JID(options.jid)
@ -460,10 +460,10 @@ option does not affect login credentials.'''.replace(
zulipToJabber.set_jabber_client(xmpp)
xmpp.process(block=False)
if options.mode == 'public':
event_types = ['stream']
if options.mode == "public":
event_types = ["stream"]
else:
event_types = ['message', 'subscription']
event_types = ["message", "subscription"]
try:
logging.info("Connecting to Zulip.")