2014-01-22 16:46:25 +01:00
|
|
|
#!/usr/bin/python
|
|
|
|
#
|
|
|
|
# Copyright (C) 2013 Permabit, Inc.
|
2014-02-21 19:24:52 +01:00
|
|
|
# Copyright (C) 2013--2014 Zulip, Inc.
|
2014-01-22 16:46:25 +01:00
|
|
|
#
|
|
|
|
# Permission is hereby granted, free of charge, to any person
|
|
|
|
# obtaining a copy of this software and associated documentation files
|
|
|
|
# (the "Software"), to deal in the Software without restriction,
|
|
|
|
# including without limitation the rights to use, copy, modify, merge,
|
|
|
|
# publish, distribute, sublicense, and/or sell copies of the Software,
|
|
|
|
# and to permit persons to whom the Software is furnished to do so,
|
|
|
|
# subject to the following conditions:
|
|
|
|
#
|
|
|
|
# The above copyright notice and this permission notice shall be
|
|
|
|
# included in all copies or substantial portions of the Software.
|
|
|
|
#
|
|
|
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
|
|
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
|
|
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
|
|
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
|
|
|
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
|
|
|
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
|
|
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
|
|
# SOFTWARE.
|
|
|
|
|
2014-02-28 21:35:26 +01:00
|
|
|
# The following is a table showing which kinds of messages are handled by the
|
|
|
|
# mirror in each mode:
|
|
|
|
#
|
|
|
|
# Message origin/type --> | Jabber | Zulip
|
|
|
|
# Mode/sender-, +-----+----+--------+----
|
|
|
|
# V | MUC | PM | stream | PM
|
|
|
|
# --------------+-------------+-----+----+--------+----
|
|
|
|
# | other sender| | x | |
|
|
|
|
# personal mode +-------------+-----+----+--------+----
|
|
|
|
# | self sender | | x | x | x
|
|
|
|
# ------------- +-------------+-----+----+--------+----
|
|
|
|
# | other sender| x | | |
|
|
|
|
# public mode +-------------+-----+----+--------+----
|
|
|
|
# | self sender | | | |
|
|
|
|
|
2014-01-22 16:46:25 +01:00
|
|
|
import logging
|
|
|
|
import threading
|
|
|
|
import optparse
|
|
|
|
|
2014-03-03 05:52:39 +01:00
|
|
|
from sleekxmpp import ClientXMPP, InvalidJID
|
2014-01-22 16:46:25 +01:00
|
|
|
from sleekxmpp.exceptions import IqError, IqTimeout
|
|
|
|
import os, sys, zulip, getpass
|
|
|
|
import re
|
|
|
|
|
2014-02-28 20:55:04 +01:00
|
|
|
__version__ = "1.1"
|
|
|
|
|
2014-01-22 16:46:25 +01:00
|
|
|
def room_to_stream(room):
|
2014-02-28 21:11:41 +01:00
|
|
|
return str(room).rpartition("@")[0] + "/xmpp"
|
|
|
|
|
|
|
|
def stream_to_room(stream):
|
2014-03-02 06:49:46 +01:00
|
|
|
return stream.lower().rpartition("/xmpp")[0]
|
2014-02-21 19:30:31 +01:00
|
|
|
|
|
|
|
def jid_to_zulip(jid):
|
|
|
|
return "%s@%s" % (str(jid).rpartition("@")[0], options.zulip_domain)
|
2014-01-22 16:46:25 +01:00
|
|
|
|
|
|
|
class JabberToZulipBot(ClientXMPP):
|
2014-02-28 18:51:07 +01:00
|
|
|
def __init__(self, nick, domain, password, rooms, openfire=False):
|
2014-01-22 16:46:25 +01:00
|
|
|
self.nick = nick
|
2014-02-28 18:51:07 +01:00
|
|
|
jid = "%s@%s/jabber_mirror" % (nick, domain)
|
2014-01-22 16:46:25 +01:00
|
|
|
ClientXMPP.__init__(self, jid, password)
|
|
|
|
self.password = password
|
2014-03-02 06:49:46 +01:00
|
|
|
self.rooms = set()
|
|
|
|
self.rooms_to_join = rooms
|
2014-01-22 16:46:25 +01:00
|
|
|
self.add_event_handler("session_start", self.session_start)
|
|
|
|
self.add_event_handler("message", self.message)
|
|
|
|
self.password = password
|
|
|
|
self.zulip = None
|
|
|
|
self.use_ipv6 = False
|
|
|
|
|
2014-02-28 19:58:04 +01:00
|
|
|
self.register_plugin('xep_0045') # Jabber chatrooms
|
|
|
|
self.register_plugin('xep_0199') # XMPP Ping
|
2014-01-22 16:46:25 +01:00
|
|
|
|
|
|
|
if openfire:
|
|
|
|
# OpenFire Jabber servers use a different SSL protocol version
|
|
|
|
import ssl
|
|
|
|
self.ssl_version = ssl.PROTOCOL_SSLv3
|
|
|
|
|
2014-02-21 19:31:10 +01:00
|
|
|
def set_zulip_client(self, client):
|
2014-01-22 16:46:25 +01:00
|
|
|
self.zulip = client
|
|
|
|
|
|
|
|
def session_start(self, event):
|
|
|
|
self.get_roster()
|
|
|
|
self.send_presence()
|
2014-03-02 06:49:46 +01:00
|
|
|
for room in self.rooms_to_join:
|
|
|
|
self.join_muc(room)
|
|
|
|
|
|
|
|
def join_muc(self, room):
|
|
|
|
if room in self.rooms:
|
|
|
|
return
|
|
|
|
logging.debug("Joining " + room)
|
|
|
|
self.rooms.add(room)
|
|
|
|
muc_jid = room + "@" + options.conference_domain
|
2014-03-03 05:47:25 +01:00
|
|
|
xep0045 = self.plugin['xep_0045']
|
2014-03-03 05:52:39 +01:00
|
|
|
try:
|
|
|
|
xep0045.joinMUC(muc_jid, self.nick, wait=True)
|
|
|
|
except InvalidJID:
|
|
|
|
logging.error("Could not join room: " + muc_jid)
|
|
|
|
return
|
2014-03-03 05:47:25 +01:00
|
|
|
|
|
|
|
# Configure the room. Really, we should only do this if the room is
|
|
|
|
# newly created.
|
|
|
|
form = None
|
|
|
|
try:
|
|
|
|
form = xep0045.getRoomConfig(muc_jid)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
if form:
|
|
|
|
xep0045.configureRoom(muc_jid, form)
|
|
|
|
else:
|
|
|
|
logging.error("Could not configure room: " + muc_jid)
|
2014-03-02 06:49:46 +01:00
|
|
|
|
|
|
|
def leave_muc(self, room):
|
|
|
|
if room not in self.rooms:
|
|
|
|
return
|
|
|
|
logging.debug("Leaving " + room)
|
|
|
|
self.rooms.remove(room)
|
|
|
|
muc_jid = room + "@" + options.conference_domain
|
|
|
|
self.plugin['xep_0045'].leaveMUC(muc_jid, self.nick)
|
2014-01-22 16:46:25 +01:00
|
|
|
|
|
|
|
def message(self, msg):
|
|
|
|
try:
|
|
|
|
if msg["type"] == "groupchat":
|
|
|
|
return self.group(msg)
|
|
|
|
elif msg["type"] == "chat":
|
|
|
|
return self.private(msg)
|
|
|
|
else:
|
|
|
|
logging.warning("Got unexpected message type")
|
|
|
|
logging.warning(msg)
|
|
|
|
except Exception:
|
|
|
|
logging.exception("Error forwarding Jabber => Zulip")
|
|
|
|
|
|
|
|
def private(self, msg):
|
2014-03-03 04:43:16 +01:00
|
|
|
if options.mode == 'public' or msg['thread'] == u'\u1FFFE':
|
2014-01-22 16:46:25 +01:00
|
|
|
return
|
2014-02-21 19:30:31 +01:00
|
|
|
sender = jid_to_zulip(msg["from"])
|
|
|
|
recipient = jid_to_zulip(msg["to"])
|
2014-01-22 16:46:25 +01:00
|
|
|
|
|
|
|
zulip_message = dict(
|
|
|
|
sender = sender,
|
|
|
|
type = "private",
|
|
|
|
to = recipient,
|
|
|
|
content = msg["body"],
|
|
|
|
)
|
2014-02-21 21:16:46 +01:00
|
|
|
ret = self.zulip.client.send_message(zulip_message)
|
2014-01-22 16:46:25 +01:00
|
|
|
if ret.get("status") != "success":
|
|
|
|
logging.error(ret)
|
|
|
|
|
|
|
|
def group(self, msg):
|
2014-03-03 04:43:16 +01:00
|
|
|
if options.mode == 'personal' or msg["thread"] == u'\u1FFFE':
|
2014-01-22 16:46:25 +01:00
|
|
|
return
|
|
|
|
|
|
|
|
subject = msg["subject"]
|
|
|
|
if len(subject) == 0:
|
|
|
|
subject = "(no topic)"
|
|
|
|
stream = room_to_stream(msg.get_mucroom())
|
|
|
|
jid = self.nickname_to_jid(msg.get_mucroom(), msg.get_mucnick())
|
2014-03-03 05:00:26 +01:00
|
|
|
if str(jid) == "@" + options.jabber_domain:
|
|
|
|
# Messages from the room itself have no nickname. We should not try
|
|
|
|
# to mirror these
|
|
|
|
return
|
2014-02-21 19:30:31 +01:00
|
|
|
sender = jid_to_zulip(jid)
|
2014-01-22 16:46:25 +01:00
|
|
|
zulip_message = dict(
|
|
|
|
forged = "yes",
|
|
|
|
sender = sender,
|
|
|
|
type = "stream",
|
|
|
|
subject = subject,
|
|
|
|
to = stream,
|
|
|
|
content = msg["body"],
|
|
|
|
)
|
2014-02-21 21:16:46 +01:00
|
|
|
ret = self.zulip.client.send_message(zulip_message)
|
2014-01-22 16:46:25 +01:00
|
|
|
if ret.get("status") != "success":
|
|
|
|
logging.error(ret)
|
|
|
|
|
|
|
|
def nickname_to_jid(self, room, nick):
|
|
|
|
jid = self.plugin['xep_0045'].getJidProperty(room, nick, "jid")
|
|
|
|
if (jid is None or jid == ''):
|
2014-02-21 19:31:41 +01:00
|
|
|
return nick.replace(' ', '') + "@" + options.jabber_domain
|
2014-01-22 16:46:25 +01:00
|
|
|
else:
|
|
|
|
return jid
|
|
|
|
|
2014-02-21 21:16:46 +01:00
|
|
|
class ZulipToJabberBot(object):
|
|
|
|
def __init__(self, zulip_client):
|
|
|
|
self.client = zulip_client
|
2014-01-22 16:46:25 +01:00
|
|
|
self.jabber = None
|
|
|
|
|
2014-02-21 19:31:10 +01:00
|
|
|
def set_jabber_client(self, client):
|
2014-01-22 16:46:25 +01:00
|
|
|
self.jabber = client
|
|
|
|
|
2014-03-02 06:49:46 +01:00
|
|
|
def process_event(self, event):
|
|
|
|
if event['type'] == 'message':
|
2014-01-22 16:46:25 +01:00
|
|
|
message = event["message"]
|
2014-02-21 21:16:46 +01:00
|
|
|
if message['sender_email'] != self.client.email:
|
2014-01-22 16:46:25 +01:00
|
|
|
return
|
2014-03-02 06:49:46 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
if message['type'] == 'stream':
|
|
|
|
self.stream_message(message)
|
|
|
|
elif message['type'] == 'private':
|
|
|
|
self.private_message(message)
|
|
|
|
except:
|
|
|
|
logging.exception("Exception forwarding Zulip => Jabber")
|
|
|
|
elif event['type'] == 'subscription':
|
|
|
|
self.process_subscription(event)
|
|
|
|
elif event['type'] == 'stream':
|
|
|
|
self.process_stream(event)
|
2014-01-22 16:46:25 +01:00
|
|
|
|
|
|
|
def stream_message(self, msg):
|
2014-02-28 21:15:43 +01:00
|
|
|
stream = msg['display_recipient']
|
|
|
|
if not stream.endswith("/xmpp"):
|
|
|
|
return
|
|
|
|
|
|
|
|
room = stream_to_room(stream)
|
2014-02-28 21:11:41 +01:00
|
|
|
jabber_recipient = "%s@%s" % (room, options.conference_domain)
|
2014-01-22 16:46:25 +01:00
|
|
|
outgoing = self.jabber.make_message(
|
|
|
|
mto = jabber_recipient,
|
|
|
|
mbody = msg['content'],
|
|
|
|
mtype = 'groupchat')
|
2014-03-03 04:43:16 +01:00
|
|
|
outgoing['thread'] = u'\u1FFFE'
|
2014-01-22 16:46:25 +01:00
|
|
|
outgoing.send()
|
|
|
|
|
|
|
|
def private_message(self, msg):
|
|
|
|
for recipient in msg['display_recipient']:
|
2014-02-21 21:16:46 +01:00
|
|
|
if recipient["email"] == self.client.email:
|
2014-01-22 16:46:25 +01:00
|
|
|
continue
|
2014-02-21 19:32:18 +01:00
|
|
|
recip_email = recipient['email']
|
|
|
|
username = recip_email[:recip_email.rfind(options.zulip_domain)]
|
|
|
|
jabber_recipient = username + options.jabber_domain
|
2014-01-22 16:46:25 +01:00
|
|
|
outgoing = self.jabber.make_message(
|
|
|
|
mto = jabber_recipient,
|
|
|
|
mbody = msg['content'],
|
|
|
|
mtype = 'chat')
|
2014-03-03 04:43:16 +01:00
|
|
|
outgoing['thread'] = u'\u1FFFE'
|
2014-01-22 16:46:25 +01:00
|
|
|
outgoing.send()
|
|
|
|
|
2014-03-02 06:49:46 +01:00
|
|
|
def process_subscription(self, event):
|
|
|
|
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']]
|
|
|
|
streams = [s for s in streams if s.endswith("/xmpp")]
|
|
|
|
for stream in streams:
|
|
|
|
self.jabber.leave_muc(stream_to_room(stream))
|
|
|
|
|
|
|
|
def process_stream(self, event):
|
|
|
|
if event['op'] == 'occupy':
|
|
|
|
streams = [s['name'].lower() for s in event['streams']]
|
|
|
|
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'] == 'vacate':
|
|
|
|
streams = [s['name'].lower() for s in event['streams']]
|
|
|
|
streams = [s for s in streams if s.endswith("/xmpp")]
|
|
|
|
for stream in streams:
|
|
|
|
self.jabber.leave_muc(stream_to_room(stream))
|
|
|
|
|
2014-03-02 04:42:20 +01:00
|
|
|
def get_rooms(zulip):
|
|
|
|
if options.mode == 'public':
|
|
|
|
stream_infos = zulip.client.get_streams()['streams']
|
|
|
|
else:
|
|
|
|
stream_infos = zulip.client.list_subscriptions()['subscriptions']
|
|
|
|
|
|
|
|
rooms = []
|
|
|
|
for stream_info in stream_infos:
|
|
|
|
stream = stream_info['name']
|
|
|
|
if stream.endswith("/xmpp"):
|
|
|
|
rooms.append(stream_to_room(stream))
|
|
|
|
return rooms
|
|
|
|
|
2014-01-22 16:46:25 +01:00
|
|
|
if __name__ == '__main__':
|
|
|
|
parser = optparse.OptionParser()
|
2014-02-26 17:27:00 +01:00
|
|
|
parser.add_option('--mode',
|
|
|
|
default="personal",
|
|
|
|
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
|
|
|
|
Zulip. In "public" mode, the mirror uses the credentials for a dedicated mirror
|
|
|
|
user and mirrors messages sent to Jabber rooms to Zulip.'''.replace("\n", " "))
|
2014-02-28 20:05:01 +01:00
|
|
|
parser.add_option('-d', '--debug',
|
|
|
|
help='set logging to DEBUG',
|
|
|
|
action='store_const',
|
|
|
|
dest='log_level',
|
|
|
|
const=logging.DEBUG,
|
|
|
|
default=logging.INFO)
|
2014-02-21 20:28:12 +01:00
|
|
|
|
2014-02-21 21:16:09 +01:00
|
|
|
jabber_group = optparse.OptionGroup(parser, "Jabber configuration")
|
2014-03-03 07:38:35 +01:00
|
|
|
jabber_group.add_option('--jabber-username',
|
|
|
|
default=None,
|
|
|
|
action='store',
|
|
|
|
help="Your Jabber username")
|
2014-02-21 21:16:09 +01:00
|
|
|
jabber_group.add_option('--jabber-password',
|
|
|
|
default=None,
|
|
|
|
action='store',
|
|
|
|
help="Your Jabber password")
|
|
|
|
jabber_group.add_option('--jabber-domain',
|
|
|
|
default=None,
|
|
|
|
action='store',
|
|
|
|
help="Your Jabber server")
|
|
|
|
jabber_group.add_option('--conference-domain',
|
|
|
|
default=None,
|
|
|
|
action='store',
|
2014-02-26 17:27:00 +01:00
|
|
|
help="Your Jabber conference domain (E.g. conference.jabber.example.com). "
|
2014-03-03 06:52:00 +01:00
|
|
|
+ "Required when running in \"public\" mode.")
|
|
|
|
jabber_group.add_option('--openfire',
|
|
|
|
default=None,
|
|
|
|
action='store_true',
|
|
|
|
help="Set if Jabber server is an OpenFire server")
|
|
|
|
jabber_group.add_option('--no-use-tls',
|
|
|
|
default=None,
|
|
|
|
action='store_true')
|
2014-02-21 21:16:09 +01:00
|
|
|
|
|
|
|
parser.add_option_group(jabber_group)
|
2014-02-21 20:28:12 +01:00
|
|
|
parser.add_option_group(zulip.generate_option_group(parser, "zulip-"))
|
2014-01-22 16:46:25 +01:00
|
|
|
(options, args) = parser.parse_args()
|
|
|
|
|
2014-02-28 20:05:01 +01:00
|
|
|
logging.basicConfig(level=options.log_level,
|
|
|
|
format='%(levelname)-8s %(message)s')
|
|
|
|
|
2014-02-26 17:27:00 +01:00
|
|
|
if options.mode not in ('public', 'personal'):
|
|
|
|
sys.exit("Bad value for --mode: must be one of 'public' or 'personal'")
|
|
|
|
|
2014-02-26 21:23:47 +01:00
|
|
|
if options.mode == 'public' and options.conference_domain is None:
|
|
|
|
sys.exit("--conference-domain is required when running in 'public' mode")
|
|
|
|
|
2014-02-21 21:16:09 +01:00
|
|
|
if options.jabber_password is None:
|
|
|
|
options.jabber_password = getpass.getpass("Jabber password: ")
|
2014-01-22 16:46:25 +01:00
|
|
|
if options.jabber_domain is None:
|
|
|
|
sys.exit("Must specify a Jabber server")
|
|
|
|
|
2014-02-28 18:51:07 +01:00
|
|
|
|
|
|
|
# This won't work for open realms
|
|
|
|
options.zulip_domain = options.zulip_email.partition('@')[-1]
|
2014-01-22 16:46:25 +01:00
|
|
|
|
2014-02-28 20:55:04 +01:00
|
|
|
zulip = ZulipToJabberBot(zulip.init_from_options(options, "JabberMirror/" + __version__))
|
2014-02-28 18:51:07 +01:00
|
|
|
xmpp = JabberToZulipBot(options.jabber_username, options.jabber_domain,
|
2014-03-02 04:42:20 +01:00
|
|
|
options.jabber_password, get_rooms(zulip),
|
2014-01-22 16:46:25 +01:00
|
|
|
openfire=options.openfire)
|
2014-02-28 20:00:03 +01:00
|
|
|
|
|
|
|
if not xmpp.connect(use_tls=not options.no_use_tls):
|
|
|
|
sys.exit("Unable to connect to Jabber server")
|
|
|
|
|
2014-02-21 19:31:10 +01:00
|
|
|
xmpp.set_zulip_client(zulip)
|
|
|
|
zulip.set_jabber_client(xmpp)
|
2014-02-28 18:51:07 +01:00
|
|
|
|
2014-03-02 06:49:46 +01:00
|
|
|
xmpp.process(block=False)
|
2014-02-28 18:51:07 +01:00
|
|
|
if options.mode == 'public':
|
2014-03-02 06:49:46 +01:00
|
|
|
event_types = ['stream']
|
2014-02-28 18:51:07 +01:00
|
|
|
else:
|
2014-03-02 06:49:46 +01:00
|
|
|
event_types = ['message', 'subscription']
|
|
|
|
|
|
|
|
try:
|
|
|
|
logging.info("Connecting to Zulip.")
|
|
|
|
zulip.client.call_on_each_event(zulip.process_event,
|
|
|
|
event_types=event_types)
|
|
|
|
except BaseException as e:
|
|
|
|
logging.exception("Exception in main loop")
|
|
|
|
xmpp.abort()
|