2012-09-06 20:45:48 +02:00
|
|
|
#!/usr/bin/python
|
2012-09-13 02:29:26 +02:00
|
|
|
import urllib
|
|
|
|
import sys
|
|
|
|
import logging
|
|
|
|
import traceback
|
|
|
|
import simplejson
|
|
|
|
import re
|
|
|
|
import time
|
2012-09-13 03:41:52 +02:00
|
|
|
import subprocess
|
2012-09-21 21:17:25 +02:00
|
|
|
import optparse
|
2012-09-26 16:44:42 +02:00
|
|
|
import os
|
2012-09-27 22:14:14 +02:00
|
|
|
import datetime
|
2012-09-28 20:29:23 +02:00
|
|
|
import textwrap
|
2012-09-28 22:12:51 +02:00
|
|
|
from urllib2 import HTTPError
|
2012-09-26 22:46:23 +02:00
|
|
|
|
2012-09-28 20:26:56 +02:00
|
|
|
sys.path.append("/mit/tabbott/Public/python-zephyr/")
|
|
|
|
sys.path.append("/mit/tabbott/Public/python-zephyr/build/lib.linux-x86_64-2.6/")
|
2012-09-13 02:29:26 +02:00
|
|
|
|
2012-09-21 21:17:25 +02:00
|
|
|
parser = optparse.OptionParser()
|
|
|
|
parser.add_option('--forward-class-messages',
|
|
|
|
dest='forward_class_messages',
|
|
|
|
default=False,
|
|
|
|
action='store_true')
|
|
|
|
parser.add_option('--resend-log',
|
|
|
|
dest='resend_log',
|
|
|
|
default=False,
|
|
|
|
action='store_true')
|
2012-09-28 23:37:10 +02:00
|
|
|
parser.add_option('--enable-log',
|
|
|
|
dest='enable_log',
|
|
|
|
default=False,
|
|
|
|
action='store_true')
|
2012-09-21 21:17:25 +02:00
|
|
|
parser.add_option('--no-forward-personals',
|
|
|
|
dest='forward_personals',
|
|
|
|
default=True,
|
|
|
|
action='store_false')
|
2012-09-24 20:29:33 +02:00
|
|
|
parser.add_option('--forward-from-humbug',
|
|
|
|
dest='forward_to_humbug',
|
|
|
|
default=True,
|
|
|
|
action='store_false')
|
2012-10-02 21:47:59 +02:00
|
|
|
parser.add_option('--site',
|
|
|
|
dest='site',
|
|
|
|
default="https://app.humbughq.com",
|
|
|
|
action='store')
|
|
|
|
parser.add_option('--api-key',
|
|
|
|
dest='api_key',
|
|
|
|
default="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
|
|
|
action='store')
|
2012-09-21 21:17:25 +02:00
|
|
|
(options, args) = parser.parse_args()
|
|
|
|
|
2012-10-02 21:47:59 +02:00
|
|
|
sys.path.append(".")
|
|
|
|
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
|
|
|
|
import api.common
|
|
|
|
humbug_client = api.common.HumbugAPI(email=os.environ["USER"] + "@mit.edu",
|
|
|
|
api_key=options.api_key,
|
|
|
|
verbose=True,
|
|
|
|
site=options.site)
|
|
|
|
|
|
|
|
import zephyr
|
|
|
|
zephyr.init()
|
|
|
|
|
2012-10-01 20:36:08 +02:00
|
|
|
def compute_humbug_username(zephyr_username):
|
|
|
|
return zephyr_username.lower().split("@")[0] + "@mit.edu"
|
|
|
|
|
2012-09-26 16:43:53 +02:00
|
|
|
def send_humbug(zeph):
|
2012-10-03 22:32:50 +02:00
|
|
|
zeph["forged"] = "yes"
|
2012-10-01 20:36:08 +02:00
|
|
|
zeph["sender"] = compute_humbug_username(zeph["sender"])
|
2012-09-17 21:39:01 +02:00
|
|
|
zeph['fullname'] = username_to_fullname(zeph['sender'])
|
|
|
|
zeph['shortname'] = zeph['sender'].split('@')[0]
|
2012-09-27 21:17:53 +02:00
|
|
|
if "instance" in zeph:
|
|
|
|
zeph["instance"] = zeph["instance"][:30]
|
2012-09-26 21:23:52 +02:00
|
|
|
|
|
|
|
for key in zeph.keys():
|
2012-09-26 22:46:23 +02:00
|
|
|
if isinstance(zeph[key], unicode):
|
2012-10-03 22:32:50 +02:00
|
|
|
zeph[key] = zeph[key].encode("utf-8")
|
2012-09-26 22:46:23 +02:00
|
|
|
elif isinstance(zeph[key], str):
|
2012-10-03 22:32:50 +02:00
|
|
|
zeph[key] = zeph[key].decode("utf-8")
|
2012-09-28 22:12:51 +02:00
|
|
|
|
2012-10-04 22:13:47 +02:00
|
|
|
return humbug_client.send_message(zeph)
|
2012-09-06 22:10:48 +02:00
|
|
|
|
2012-09-13 03:41:52 +02:00
|
|
|
def fetch_fullname(username):
|
|
|
|
try:
|
2012-09-21 21:17:25 +02:00
|
|
|
match_user = re.match(r'([a-zA-Z0-9_]+)@mit\.edu', username)
|
2012-09-13 03:41:52 +02:00
|
|
|
if match_user:
|
|
|
|
proc = subprocess.Popen(['hesinfo', match_user.group(1), 'passwd'], stdout=subprocess.PIPE)
|
|
|
|
out, _err_unused = proc.communicate()
|
|
|
|
if proc.returncode == 0:
|
|
|
|
return out.split(':')[4].split(',')[0]
|
|
|
|
except:
|
|
|
|
print >>sys.stderr, 'Error getting fullname for', username
|
|
|
|
traceback.print_exc()
|
|
|
|
|
|
|
|
return username.title().replace('@', ' at ').replace('.', ' dot ')
|
|
|
|
|
|
|
|
fullnames = {}
|
|
|
|
def username_to_fullname(username):
|
|
|
|
if username not in fullnames:
|
|
|
|
fullnames[username] = fetch_fullname(username)
|
|
|
|
return fullnames[username]
|
|
|
|
|
2012-09-07 17:45:09 +02:00
|
|
|
|
2012-09-24 20:29:33 +02:00
|
|
|
def process_loop(log):
|
2012-09-26 17:53:41 +02:00
|
|
|
import mit_subs_list
|
2012-09-13 02:29:26 +02:00
|
|
|
while True:
|
2012-09-07 19:17:56 +02:00
|
|
|
try:
|
2012-09-13 02:29:26 +02:00
|
|
|
notice = zephyr.receive(block=True)
|
|
|
|
zsig, body = notice.message.split("\x00", 1)
|
2012-09-21 22:24:16 +02:00
|
|
|
is_personal = False
|
|
|
|
is_huddle = False
|
2012-10-03 19:48:12 +02:00
|
|
|
|
2012-10-04 23:25:49 +02:00
|
|
|
if notice.opcode == "PING":
|
2012-10-03 19:48:12 +02:00
|
|
|
# skip PING messages
|
|
|
|
continue
|
|
|
|
|
2012-09-28 21:45:11 +02:00
|
|
|
if isinstance(zsig, str):
|
|
|
|
# Check for width unicode character u'\u200B'.encode("utf-8")
|
|
|
|
if u'\u200B'.encode("utf-8") in zsig:
|
|
|
|
print "Skipping message from Humbug!"
|
|
|
|
continue
|
2012-09-24 20:29:33 +02:00
|
|
|
|
2012-09-21 22:24:16 +02:00
|
|
|
sender = notice.sender.lower().replace("athena.mit.edu", "mit.edu")
|
|
|
|
recipient = notice.recipient.lower().replace("athena.mit.edu", "mit.edu")
|
2012-09-13 02:29:26 +02:00
|
|
|
|
2012-09-28 22:15:58 +02:00
|
|
|
if (notice.cls.lower() == "message" and
|
|
|
|
notice.instance.lower() == "personal"):
|
2012-09-21 21:17:25 +02:00
|
|
|
is_personal = True
|
2012-09-21 22:24:16 +02:00
|
|
|
if body.startswith("CC:"):
|
|
|
|
is_huddle = True
|
|
|
|
# Map "CC: sipbtest espuser" => "starnine@mit.edu,espuser@mit.edu"
|
2012-10-03 19:47:54 +02:00
|
|
|
huddle_recipients_list = [compute_humbug_username(x.strip()) for x in
|
2012-09-24 20:29:33 +02:00
|
|
|
body.split("\n")[0][4:].split()]
|
2012-09-21 22:24:16 +02:00
|
|
|
if sender not in huddle_recipients_list:
|
|
|
|
huddle_recipients_list.append(sender)
|
|
|
|
huddle_recipients = ",".join(huddle_recipients_list)
|
2012-09-21 21:17:25 +02:00
|
|
|
|
|
|
|
# Drop messages not to the listed subscriptions
|
2012-09-28 22:15:58 +02:00
|
|
|
if (notice.cls.lower() not in mit_subs_list.all_subs) and not \
|
|
|
|
(is_personal and options.forward_personals):
|
2012-09-21 21:17:25 +02:00
|
|
|
print "Skipping ...", notice.cls, notice.instance, is_personal
|
|
|
|
continue
|
|
|
|
|
2012-09-21 22:24:16 +02:00
|
|
|
if is_huddle:
|
|
|
|
zeph = { 'type' : 'personal',
|
|
|
|
'time' : str(notice.time),
|
|
|
|
'sender' : sender,
|
|
|
|
'recipient' : huddle_recipients,
|
|
|
|
'zsig' : zsig, # logged here but not used by app
|
2012-10-02 23:52:41 +02:00
|
|
|
'content' : body.split("\n", 1)[1] }
|
2012-09-21 22:24:16 +02:00
|
|
|
elif is_personal:
|
2012-09-21 21:17:25 +02:00
|
|
|
zeph = { 'type' : 'personal',
|
|
|
|
'time' : str(notice.time),
|
|
|
|
'sender' : sender,
|
2012-10-03 19:47:54 +02:00
|
|
|
'recipient' : compute_humbug_username(recipient),
|
2012-09-21 21:17:25 +02:00
|
|
|
'zsig' : zsig, # logged here but not used by app
|
2012-10-02 23:52:41 +02:00
|
|
|
'content' : body }
|
2012-09-21 21:17:25 +02:00
|
|
|
else:
|
|
|
|
zeph = { 'type' : 'class',
|
|
|
|
'time' : str(notice.time),
|
|
|
|
'sender' : sender,
|
2012-09-28 22:15:58 +02:00
|
|
|
'class' : notice.cls.lower(),
|
2012-10-09 16:55:42 +02:00
|
|
|
'instance' : notice.instance.lower(),
|
2012-09-21 21:17:25 +02:00
|
|
|
'zsig' : zsig, # logged here but not used by app
|
2012-10-03 22:32:50 +02:00
|
|
|
'content' : body }
|
2012-09-13 02:29:26 +02:00
|
|
|
|
|
|
|
log.write(simplejson.dumps(zeph) + '\n')
|
|
|
|
log.flush()
|
|
|
|
|
2012-10-01 17:57:35 +02:00
|
|
|
print "%s: received a message on %s/%s from %s..." % \
|
|
|
|
(datetime.datetime.now(), notice.cls, notice.instance, notice.sender)
|
2012-10-04 22:13:47 +02:00
|
|
|
res = send_humbug(zeph)
|
|
|
|
if res.get("result") != "success":
|
|
|
|
print >>sys.stderr, 'Error relaying zephyr'
|
|
|
|
print zeph
|
|
|
|
print res
|
2012-09-07 19:17:56 +02:00
|
|
|
except:
|
2012-09-13 02:29:26 +02:00
|
|
|
print >>sys.stderr, 'Error relaying zephyr'
|
2012-09-07 19:17:56 +02:00
|
|
|
traceback.print_exc()
|
2012-09-13 02:29:26 +02:00
|
|
|
time.sleep(2)
|
2012-09-24 20:29:33 +02:00
|
|
|
|
|
|
|
|
|
|
|
def zephyr_to_humbug(options):
|
|
|
|
import mit_subs_list
|
|
|
|
subs = zephyr.Subscriptions()
|
|
|
|
if options.forward_class_messages:
|
|
|
|
for sub in mit_subs_list.all_subs:
|
|
|
|
subs.add((sub, '*', '*'))
|
|
|
|
if options.forward_personals:
|
|
|
|
subs.add(("message", "personal", "*"))
|
|
|
|
|
|
|
|
if options.resend_log:
|
|
|
|
with open('zephyrs', 'r') as log:
|
2012-09-26 21:23:52 +02:00
|
|
|
for ln in log:
|
|
|
|
try:
|
2012-09-24 20:29:33 +02:00
|
|
|
zeph = simplejson.loads(ln)
|
|
|
|
print "sending saved message to %s from %s..." % \
|
|
|
|
(zeph.get('class', zeph.get('recipient')), zeph['sender'])
|
2012-09-26 16:43:53 +02:00
|
|
|
send_humbug(zeph)
|
2012-09-26 21:23:52 +02:00
|
|
|
except:
|
|
|
|
print >>sys.stderr, 'Could not send saved zephyr'
|
|
|
|
traceback.print_exc()
|
|
|
|
time.sleep(2)
|
2012-09-24 20:29:33 +02:00
|
|
|
|
|
|
|
print "Starting receive loop"
|
|
|
|
|
2012-09-28 23:37:10 +02:00
|
|
|
if options.enable_log:
|
|
|
|
log_file = "zephyrs"
|
|
|
|
else:
|
|
|
|
log_file = "/dev/null"
|
|
|
|
|
|
|
|
with open(log_file, 'a') as log:
|
2012-09-24 20:29:33 +02:00
|
|
|
process_loop(log)
|
|
|
|
|
2012-10-02 21:47:59 +02:00
|
|
|
def forward_to_zephyr(message):
|
2012-09-28 21:45:11 +02:00
|
|
|
zsig = u"%s\u200B" % (username_to_fullname(message["sender_email"]))
|
2012-09-28 21:29:44 +02:00
|
|
|
if ' dot ' in zsig:
|
|
|
|
print "ERROR! Couldn't compute zsig for %s!" % (message["sender_email"])
|
|
|
|
return
|
2012-10-02 21:20:09 +02:00
|
|
|
|
|
|
|
content = message["content"]
|
|
|
|
cleaned_content = content.replace('<','<').replace('>','>').replace('&', '&')
|
2012-10-02 20:18:53 +02:00
|
|
|
wrapped_content = "\n".join("\n".join(textwrap.wrap(line))
|
2012-10-02 21:20:09 +02:00
|
|
|
for line in cleaned_content.split("\n"))
|
|
|
|
|
2012-09-28 20:49:59 +02:00
|
|
|
print "Sending message from %s humbug=>zephyr at %s" % (message["sender_email"], datetime.datetime.now())
|
2012-09-26 16:44:42 +02:00
|
|
|
if message['type'] == "class":
|
|
|
|
zeph = zephyr.ZNotice(sender=message["sender_email"].replace("mit.edu", "ATHENA.MIT.EDU"),
|
2012-09-27 23:53:40 +02:00
|
|
|
auth=True, cls=message["display_recipient"],
|
|
|
|
instance=message["instance"])
|
2012-09-28 20:29:23 +02:00
|
|
|
body = "%s\0%s" % (zsig, wrapped_content)
|
2012-09-27 22:14:14 +02:00
|
|
|
zeph.setmessage(body)
|
|
|
|
zeph.send()
|
2012-09-26 16:44:42 +02:00
|
|
|
elif message['type'] == "personal":
|
|
|
|
zeph = zephyr.ZNotice(sender=message["sender_email"].replace("mit.edu", "ATHENA.MIT.EDU"),
|
2012-09-27 22:14:14 +02:00
|
|
|
auth=True, recipient=message["display_recipient"].replace("mit.edu", "ATHENA.MIT.EDU"),
|
|
|
|
cls="message", instance="personal")
|
2012-09-28 20:29:23 +02:00
|
|
|
body = "%s\0%s" % (zsig, wrapped_content)
|
2012-09-27 22:14:14 +02:00
|
|
|
zeph.setmessage(body)
|
|
|
|
zeph.send()
|
2012-09-26 16:44:42 +02:00
|
|
|
elif message['type'] == "huddle":
|
|
|
|
cc_list = ["CC:"]
|
|
|
|
cc_list.extend([user["email"].replace("@mit.edu", "")
|
|
|
|
for user in message["display_recipient"]])
|
2012-09-28 20:29:23 +02:00
|
|
|
body = "%s\0%s\n%s" % (zsig, " ".join(cc_list), wrapped_content)
|
2012-09-27 22:14:14 +02:00
|
|
|
for r in message["display_recipient"]:
|
|
|
|
zeph = zephyr.ZNotice(sender=message["sender_email"].replace("mit.edu", "ATHENA.MIT.EDU"),
|
|
|
|
auth=True, recipient=r["email"].replace("mit.edu", "ATHENA.MIT.EDU"),
|
|
|
|
cls="message", instance="personal")
|
|
|
|
zeph.setmessage(body)
|
|
|
|
zeph.send()
|
2012-09-26 16:44:42 +02:00
|
|
|
|
2012-10-02 21:47:59 +02:00
|
|
|
def maybe_forward_to_zephyr(message):
|
|
|
|
if message["sender_email"] == os.environ["USER"] + "@mit.edu":
|
2012-10-03 23:08:07 +02:00
|
|
|
if float(message["timestamp"]) < float(datetime.datetime.now().strftime("%s")) - 15:
|
2012-10-02 21:47:59 +02:00
|
|
|
print "Alert! Out of order message!", message["timestamp"], datetime.datetime.now().strftime("%s")
|
|
|
|
return
|
|
|
|
forward_to_zephyr(message)
|
|
|
|
|
2012-09-24 20:29:33 +02:00
|
|
|
def humbug_to_zephyr(options):
|
|
|
|
# Sync messages from zephyr to humbug
|
2012-09-27 22:14:14 +02:00
|
|
|
print "Starting syncing messages."
|
2012-10-02 21:47:59 +02:00
|
|
|
humbug_client.call_on_each_message(maybe_forward_to_zephyr,
|
|
|
|
options={"mit_sync_bot": 'yes'})
|
2012-09-24 20:29:33 +02:00
|
|
|
|
|
|
|
if options.forward_to_humbug:
|
|
|
|
zephyr_to_humbug(options)
|
|
|
|
else:
|
|
|
|
humbug_to_zephyr(options)
|