2017-08-10 15:20:44 -04:00
|
|
|
#!/usr/bin/env python
|
|
|
|
import os
|
|
|
|
import logging
|
|
|
|
import signal
|
|
|
|
import traceback
|
2018-05-11 06:08:29 -04:00
|
|
|
import zulip
|
|
|
|
import sys
|
2018-05-21 11:01:40 -04:00
|
|
|
import argparse
|
2018-05-21 11:00:20 -04:00
|
|
|
import re
|
2018-08-06 18:07:56 -04:00
|
|
|
from six.moves import configparser
|
2017-08-10 15:20:44 -04:00
|
|
|
|
2018-06-01 22:15:00 -04:00
|
|
|
from collections import OrderedDict
|
|
|
|
|
2017-08-10 15:20:44 -04:00
|
|
|
from types import FrameType
|
2018-05-21 11:01:40 -04:00
|
|
|
from typing import Any, Callable, Dict, Optional
|
2017-08-10 15:20:44 -04:00
|
|
|
|
2018-06-01 18:45:19 -04:00
|
|
|
from matrix_client.errors import MatrixRequestError
|
2017-08-10 15:20:44 -04:00
|
|
|
from matrix_client.client import MatrixClient
|
2018-05-11 06:21:27 -04:00
|
|
|
from requests.exceptions import MissingSchema
|
|
|
|
|
2018-05-21 11:00:20 -04:00
|
|
|
GENERAL_NETWORK_USERNAME_REGEX = '@_?[a-zA-Z0-9]+_([a-zA-Z0-9-_]+):[a-zA-Z0-9.]+'
|
|
|
|
MATRIX_USERNAME_REGEX = '@([a-zA-Z0-9-_]+):matrix.org'
|
|
|
|
|
|
|
|
# change these templates to change the format of displayed message
|
|
|
|
ZULIP_MESSAGE_TEMPLATE = "**{username}**: {message}"
|
|
|
|
MATRIX_MESSAGE_TEMPLATE = "<{username}> {message}"
|
|
|
|
|
2018-05-31 13:29:00 -04:00
|
|
|
class Bridge_ConfigException(Exception):
|
|
|
|
pass
|
|
|
|
|
2018-06-01 18:45:19 -04:00
|
|
|
class Bridge_FatalMatrixException(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class Bridge_ZulipFatalException(Exception):
|
|
|
|
pass
|
|
|
|
|
2018-06-02 22:37:16 -04:00
|
|
|
def matrix_login(matrix_client, matrix_config):
|
|
|
|
# type: (Any, Dict[str, Any]) -> None
|
2018-05-11 06:21:27 -04:00
|
|
|
try:
|
|
|
|
matrix_client.login_with_password(matrix_config["username"],
|
|
|
|
matrix_config["password"])
|
2018-06-01 18:45:19 -04:00
|
|
|
except MatrixRequestError as exception:
|
|
|
|
if exception.code == 403:
|
|
|
|
raise Bridge_FatalMatrixException("Bad username or password.")
|
2018-05-11 06:21:27 -04:00
|
|
|
else:
|
2018-06-01 18:45:19 -04:00
|
|
|
raise Bridge_FatalMatrixException("Check if your server details are correct.")
|
|
|
|
except MissingSchema as exception:
|
|
|
|
raise Bridge_FatalMatrixException("Bad URL format.")
|
2018-05-11 06:21:27 -04:00
|
|
|
|
2018-06-02 22:37:16 -04:00
|
|
|
def matrix_join_room(matrix_client, matrix_config):
|
|
|
|
# type: (Any, Dict[str, Any]) -> Any
|
2018-05-11 06:21:27 -04:00
|
|
|
try:
|
|
|
|
room = matrix_client.join_room(matrix_config["room_id"])
|
|
|
|
return room
|
2018-06-01 18:45:19 -04:00
|
|
|
except MatrixRequestError as exception:
|
|
|
|
if exception.code == 403:
|
|
|
|
raise Bridge_FatalMatrixException("Room ID/Alias in the wrong format")
|
2018-05-11 06:21:27 -04:00
|
|
|
else:
|
2018-06-01 18:45:19 -04:00
|
|
|
raise Bridge_FatalMatrixException("Couldn't find room.")
|
2017-08-10 15:20:44 -04:00
|
|
|
|
2018-06-02 22:37:16 -04:00
|
|
|
def die(signal, frame):
|
|
|
|
# type: (int, FrameType) -> None
|
2017-08-10 15:20:44 -04:00
|
|
|
# We actually want to exit, so run os._exit (so as not to be caught and restarted)
|
|
|
|
os._exit(1)
|
|
|
|
|
2018-06-02 22:37:16 -04:00
|
|
|
def matrix_to_zulip(zulip_client, zulip_config, matrix_config, no_noise):
|
|
|
|
# type: (zulip.Client, Dict[str, Any], Dict[str, Any], bool) -> Callable[[Any, Dict[str, Any]], None]
|
|
|
|
def _matrix_to_zulip(room, event):
|
|
|
|
# type: (Any, Dict[str, Any]) -> None
|
2017-08-10 15:20:44 -04:00
|
|
|
"""
|
2018-05-11 06:08:29 -04:00
|
|
|
Matrix -> Zulip
|
|
|
|
"""
|
2018-05-21 11:01:40 -04:00
|
|
|
content = get_message_content_from_event(event, no_noise)
|
2018-05-11 06:08:29 -04:00
|
|
|
|
|
|
|
zulip_bot_user = ('@%s:matrix.org' % matrix_config['username'])
|
|
|
|
# We do this to identify the messages generated from Zulip -> Matrix
|
|
|
|
# and we make sure we don't forward it again to the Zulip stream.
|
|
|
|
not_from_zulip_bot = ('body' not in event['content'] or
|
|
|
|
event['sender'] != zulip_bot_user)
|
|
|
|
|
2018-05-21 11:01:40 -04:00
|
|
|
if not_from_zulip_bot and content:
|
2018-05-11 06:08:29 -04:00
|
|
|
try:
|
|
|
|
result = zulip_client.send_message({
|
|
|
|
"sender": zulip_client.email,
|
|
|
|
"type": "stream",
|
|
|
|
"to": zulip_config["stream"],
|
2018-05-21 11:18:30 -04:00
|
|
|
"subject": zulip_config["topic"],
|
2018-05-11 06:08:29 -04:00
|
|
|
"content": content,
|
|
|
|
})
|
2018-06-01 18:45:19 -04:00
|
|
|
except Exception as exception: # XXX This should be more specific
|
2018-05-11 06:08:29 -04:00
|
|
|
# Generally raised when user is forbidden
|
2018-06-01 18:45:19 -04:00
|
|
|
raise Bridge_ZulipFatalException(exception)
|
2018-05-11 06:08:29 -04:00
|
|
|
if result['result'] != 'success':
|
|
|
|
# Generally raised when API key is invalid
|
2018-06-01 18:45:19 -04:00
|
|
|
raise Bridge_ZulipFatalException(result['msg'])
|
2018-05-11 06:08:29 -04:00
|
|
|
|
2017-08-10 15:20:44 -04:00
|
|
|
return _matrix_to_zulip
|
|
|
|
|
2018-06-02 22:37:16 -04:00
|
|
|
def get_message_content_from_event(event, no_noise):
|
|
|
|
# type: (Dict[str, Any], bool) -> Optional[str]
|
2018-05-21 11:00:20 -04:00
|
|
|
irc_nick = shorten_irc_nick(event['sender'])
|
2018-05-11 06:08:29 -04:00
|
|
|
if event['type'] == "m.room.member":
|
2018-05-21 11:01:40 -04:00
|
|
|
if no_noise:
|
|
|
|
return None
|
|
|
|
# Join and leave events can be noisy. They are ignored by default.
|
|
|
|
# To enable these events pass `no_noise` as `False` as the script argument
|
2018-05-11 06:08:29 -04:00
|
|
|
if event['membership'] == "join":
|
2018-05-21 11:00:20 -04:00
|
|
|
content = ZULIP_MESSAGE_TEMPLATE.format(username=irc_nick,
|
|
|
|
message="joined")
|
2018-05-11 06:08:29 -04:00
|
|
|
elif event['membership'] == "leave":
|
2018-05-21 11:00:20 -04:00
|
|
|
content = ZULIP_MESSAGE_TEMPLATE.format(username=irc_nick,
|
|
|
|
message="quit")
|
2018-05-11 06:08:29 -04:00
|
|
|
elif event['type'] == "m.room.message":
|
|
|
|
if event['content']['msgtype'] == "m.text" or event['content']['msgtype'] == "m.emote":
|
2018-05-21 11:00:20 -04:00
|
|
|
content = ZULIP_MESSAGE_TEMPLATE.format(username=irc_nick,
|
|
|
|
message=event['content']['body'])
|
2018-05-11 06:08:29 -04:00
|
|
|
else:
|
|
|
|
content = event['type']
|
|
|
|
return content
|
|
|
|
|
2018-06-02 22:37:16 -04:00
|
|
|
def shorten_irc_nick(nick):
|
|
|
|
# type: (str) -> str
|
2018-05-21 11:00:20 -04:00
|
|
|
"""
|
|
|
|
Add nick shortner functions for specific IRC networks
|
|
|
|
Eg: For freenode change '@freenode_user:matrix.org' to 'user'
|
|
|
|
Check the list of IRC networks here:
|
|
|
|
https://github.com/matrix-org/matrix-appservice-irc/wiki/Bridged-IRC-networks
|
|
|
|
"""
|
|
|
|
match = re.match(GENERAL_NETWORK_USERNAME_REGEX, nick)
|
|
|
|
if match:
|
|
|
|
return match.group(1)
|
|
|
|
# For matrix users
|
|
|
|
match = re.match(MATRIX_USERNAME_REGEX, nick)
|
|
|
|
if match:
|
|
|
|
return match.group(1)
|
|
|
|
return nick
|
|
|
|
|
2018-06-02 22:37:16 -04:00
|
|
|
def zulip_to_matrix(config, room):
|
|
|
|
# type: (Dict[str, Any], Any) -> Callable[[Dict[str, Any]], None]
|
2017-08-10 15:20:44 -04:00
|
|
|
|
2018-06-02 22:37:16 -04:00
|
|
|
def _zulip_to_matrix(msg):
|
|
|
|
# type: (Dict[str, Any]) -> None
|
2018-05-11 06:08:29 -04:00
|
|
|
"""
|
|
|
|
Zulip -> Matrix
|
2017-08-10 15:20:44 -04:00
|
|
|
"""
|
2018-05-15 04:54:01 -04:00
|
|
|
message_valid = check_zulip_message_validity(msg, config)
|
|
|
|
if message_valid:
|
2018-05-21 11:00:20 -04:00
|
|
|
matrix_username = msg["sender_full_name"].replace(' ', '')
|
|
|
|
matrix_text = MATRIX_MESSAGE_TEMPLATE.format(username=matrix_username,
|
|
|
|
message=msg["content"])
|
2018-05-15 04:54:01 -04:00
|
|
|
# Forward Zulip message to Matrix
|
2017-08-10 15:20:44 -04:00
|
|
|
room.send_text(matrix_text)
|
|
|
|
return _zulip_to_matrix
|
|
|
|
|
2018-06-02 22:37:16 -04:00
|
|
|
def check_zulip_message_validity(msg, config):
|
|
|
|
# type: (Dict[str, Any], Dict[str, Any]) -> bool
|
2018-05-15 04:54:01 -04:00
|
|
|
is_a_stream = msg["type"] == "stream"
|
|
|
|
in_the_specified_stream = msg["display_recipient"] == config["stream"]
|
2018-05-21 11:18:30 -04:00
|
|
|
at_the_specified_subject = msg["subject"] == config["topic"]
|
2018-05-15 04:54:01 -04:00
|
|
|
|
|
|
|
# We do this to identify the messages generated from Matrix -> Zulip
|
|
|
|
# and we make sure we don't forward it again to the Matrix.
|
|
|
|
not_from_zulip_bot = msg["sender_email"] != config["email"]
|
|
|
|
if is_a_stream and not_from_zulip_bot and in_the_specified_stream and at_the_specified_subject:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2018-06-02 22:37:16 -04:00
|
|
|
def generate_parser():
|
|
|
|
# type: () -> argparse.ArgumentParser
|
2018-06-01 21:05:54 -04:00
|
|
|
description = """
|
|
|
|
Script to bridge between a topic in a Zulip stream, and a Matrix channel.
|
|
|
|
|
|
|
|
Tested connections:
|
|
|
|
* Zulip <-> Matrix channel
|
|
|
|
* Zulip <-> IRC channel (bridged via Matrix)
|
|
|
|
|
|
|
|
Example matrix 'room_id' options might be, if via matrix.org:
|
|
|
|
* #zulip:matrix.org (zulip channel on Matrix)
|
|
|
|
* #freenode_#zulip:matrix.org (zulip channel on irc.freenode.net)"""
|
|
|
|
|
|
|
|
parser = argparse.ArgumentParser(description=description,
|
|
|
|
formatter_class=argparse.RawTextHelpFormatter)
|
2018-06-01 22:15:00 -04:00
|
|
|
parser.add_argument('-c', '--config', required=False,
|
2018-05-31 13:29:00 -04:00
|
|
|
help="Path to the config file for the bridge.")
|
2018-06-01 22:15:00 -04:00
|
|
|
parser.add_argument('--write-sample-config', metavar='PATH', dest='sample_config',
|
|
|
|
help="Generate a configuration template at the specified location.")
|
2018-06-02 23:25:33 -04:00
|
|
|
parser.add_argument('--from-zuliprc', metavar='ZULIPRC', dest='zuliprc',
|
|
|
|
help="Optional path to zuliprc file for bot, when using --write-sample-config")
|
2018-06-01 18:02:09 -04:00
|
|
|
parser.add_argument('--show-join-leave', dest='no_noise',
|
|
|
|
default=True, action='store_false',
|
|
|
|
help="Enable IRC join/leave events.")
|
2018-06-01 22:15:00 -04:00
|
|
|
return parser
|
2018-05-21 11:01:40 -04:00
|
|
|
|
2018-06-02 22:37:16 -04:00
|
|
|
def read_configuration(config_file):
|
|
|
|
# type: (str) -> Dict[str, Dict[str, str]]
|
2018-05-31 13:29:00 -04:00
|
|
|
config = configparser.ConfigParser()
|
|
|
|
|
|
|
|
try:
|
|
|
|
config.read(config_file)
|
2018-06-01 18:45:19 -04:00
|
|
|
except configparser.Error as exception:
|
|
|
|
raise Bridge_ConfigException(str(exception))
|
2018-05-31 13:29:00 -04:00
|
|
|
|
|
|
|
if set(config.sections()) != {'matrix', 'zulip'}:
|
|
|
|
raise Bridge_ConfigException("Please ensure the configuration has zulip & matrix sections.")
|
|
|
|
|
|
|
|
# TODO Could add more checks for configuration content here
|
|
|
|
|
|
|
|
return {section: dict(config[section]) for section in config.sections()}
|
|
|
|
|
2018-06-02 23:25:33 -04:00
|
|
|
def write_sample_config(target_path, zuliprc):
|
|
|
|
# type: (str, Optional[str]) -> None
|
2018-06-01 22:15:00 -04:00
|
|
|
if os.path.exists(target_path):
|
|
|
|
raise Bridge_ConfigException("Path '{}' exists; not overwriting existing file.".format(target_path))
|
|
|
|
|
|
|
|
sample_dict = OrderedDict((
|
|
|
|
('matrix', OrderedDict((
|
|
|
|
('host', 'https://matrix.org'),
|
|
|
|
('username', 'username'),
|
|
|
|
('password', 'password'),
|
|
|
|
('room_id', '#zulip:matrix.org'),
|
|
|
|
))),
|
|
|
|
('zulip', OrderedDict((
|
|
|
|
('email', 'glitch-bot@chat.zulip.org'),
|
|
|
|
('api_key', 'aPiKeY'),
|
|
|
|
('site', 'https://chat.zulip.org'),
|
|
|
|
('stream', 'test here'),
|
|
|
|
('topic', 'matrix'),
|
|
|
|
))),
|
|
|
|
))
|
|
|
|
|
2018-06-02 23:25:33 -04:00
|
|
|
if zuliprc is not None:
|
|
|
|
if not os.path.exists(zuliprc):
|
|
|
|
raise Bridge_ConfigException("Zuliprc file '{}' does not exist.".format(zuliprc))
|
|
|
|
|
|
|
|
zuliprc_config = configparser.ConfigParser()
|
|
|
|
try:
|
|
|
|
zuliprc_config.read(zuliprc)
|
|
|
|
except configparser.Error as exception:
|
|
|
|
raise Bridge_ConfigException(str(exception))
|
|
|
|
|
|
|
|
# Can add more checks for validity of zuliprc file here
|
|
|
|
|
|
|
|
sample_dict['zulip']['email'] = zuliprc_config['api']['email']
|
|
|
|
sample_dict['zulip']['site'] = zuliprc_config['api']['site']
|
|
|
|
sample_dict['zulip']['api_key'] = zuliprc_config['api']['key']
|
|
|
|
|
2018-06-01 22:15:00 -04:00
|
|
|
sample = configparser.ConfigParser()
|
|
|
|
sample.read_dict(sample_dict)
|
|
|
|
with open(target_path, 'w') as target:
|
|
|
|
sample.write(target)
|
|
|
|
|
2018-06-02 22:37:16 -04:00
|
|
|
def main():
|
|
|
|
# type: () -> None
|
2017-08-10 15:20:44 -04:00
|
|
|
signal.signal(signal.SIGINT, die)
|
|
|
|
logging.basicConfig(level=logging.WARNING)
|
|
|
|
|
2018-06-01 22:15:00 -04:00
|
|
|
parser = generate_parser()
|
|
|
|
options = parser.parse_args()
|
|
|
|
|
|
|
|
if options.sample_config:
|
|
|
|
try:
|
2018-06-02 23:25:33 -04:00
|
|
|
write_sample_config(options.sample_config, options.zuliprc)
|
2018-06-01 22:15:00 -04:00
|
|
|
except Bridge_ConfigException as exception:
|
2018-06-06 01:06:28 -04:00
|
|
|
print("Could not write sample config: {}".format(exception))
|
|
|
|
sys.exit(1)
|
2018-06-02 23:25:33 -04:00
|
|
|
if options.zuliprc is None:
|
|
|
|
print("Wrote sample configuration to '{}'".format(options.sample_config))
|
|
|
|
else:
|
|
|
|
print("Wrote sample configuration to '{}' using zuliprc file '{}'"
|
|
|
|
.format(options.sample_config, options.zuliprc))
|
2018-06-01 22:15:00 -04:00
|
|
|
sys.exit(0)
|
|
|
|
elif not options.config:
|
|
|
|
print("Options required: -c or --config to run, OR --write-sample-config.")
|
|
|
|
parser.print_usage()
|
|
|
|
sys.exit(1)
|
2018-05-31 13:29:00 -04:00
|
|
|
|
|
|
|
try:
|
|
|
|
config = read_configuration(options.config)
|
|
|
|
except Bridge_ConfigException as exception:
|
2018-06-06 01:06:28 -04:00
|
|
|
print("Could not parse config file: {}".format(exception))
|
|
|
|
sys.exit(1)
|
2018-05-31 13:29:00 -04:00
|
|
|
|
|
|
|
# Get config for each client
|
2017-08-10 15:20:44 -04:00
|
|
|
zulip_config = config["zulip"]
|
|
|
|
matrix_config = config["matrix"]
|
|
|
|
|
|
|
|
# Initiate clients
|
|
|
|
backoff = zulip.RandomExponentialBackoff(timeout_success_equivalent=300)
|
|
|
|
while backoff.keep_going():
|
|
|
|
print("Starting matrix mirroring bot")
|
|
|
|
try:
|
|
|
|
zulip_client = zulip.Client(email=zulip_config["email"],
|
|
|
|
api_key=zulip_config["api_key"],
|
|
|
|
site=zulip_config["site"])
|
|
|
|
matrix_client = MatrixClient(matrix_config["host"])
|
|
|
|
|
2018-05-11 06:21:27 -04:00
|
|
|
# Login to Matrix
|
|
|
|
matrix_login(matrix_client, matrix_config)
|
|
|
|
# Join a room in Matrix
|
|
|
|
room = matrix_join_room(matrix_client, matrix_config)
|
|
|
|
|
2018-05-21 11:01:40 -04:00
|
|
|
room.add_listener(matrix_to_zulip(zulip_client, zulip_config, matrix_config,
|
|
|
|
options.no_noise))
|
2017-08-10 15:20:44 -04:00
|
|
|
|
|
|
|
print("Starting listener thread on Matrix client")
|
|
|
|
matrix_client.start_listener_thread()
|
|
|
|
|
|
|
|
print("Starting message handler on Zulip client")
|
|
|
|
zulip_client.call_on_each_message(zulip_to_matrix(zulip_config, room))
|
2018-06-01 18:45:19 -04:00
|
|
|
|
|
|
|
except Bridge_FatalMatrixException as exception:
|
|
|
|
sys.exit("Matrix bridge error: {}".format(exception))
|
|
|
|
except Bridge_ZulipFatalException as exception:
|
|
|
|
sys.exit("Zulip bridge error: {}".format(exception))
|
|
|
|
except zulip.ZulipError as exception:
|
|
|
|
sys.exit("Zulip error: {}".format(exception))
|
|
|
|
except Exception as e:
|
2017-08-10 15:20:44 -04:00
|
|
|
traceback.print_exc()
|
|
|
|
backoff.fail()
|
2018-05-31 01:48:37 -04:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|